我正在使用ajax作为后端,从服务器获取数据,我正在使用java-servlet
现在我面临的问题是:
doGet
方法编写我的所有代码url
中的ajax调用,我给了servlet类名称我要做什么
我在做什么
Servlet1代码
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String categoryCode, categoryName, quantity,sql,str = null;
Gson gson = new Gson();
LinkedHashMap<Object, Object> lhm = null;
LinkedList<LinkedHashMap<Object, Object>> mainList = new LinkedList<LinkedHashMap<Object, Object>>();
try {
sql = "1";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
lhm = new LinkedHashMap<Object, Object>();
categoryCode = "A101";
categoryName = "drinks";
lhm.put("Category Code", categoryCode);
lhm.put("Category Name", categoryName);
mainList.add(lhm);
str = gson.toJson(mainList);
}
response.setContentType("application/json");
response.getWriter().write(str);
}}
Servlet2代码
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String itemName, itemCode, quantity,sql,str = null;
Gson gson = new Gson();
LinkedHashMap<Object, Object> lhm = null;
LinkedList<LinkedHashMap<Object, Object>> mainList = new LinkedList<LinkedHashMap<Object, Object>>();
try {
sql = "2";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
lhm = new LinkedHashMap<Object, Object>();
itemName = "pepsi";
itemCode = "AA00";
lhm.put("Item Code", itemCode);
lhm.put("Item Name", itemName);
mainList.add(lhm);
str = gson.toJson(mainList);
}
response.setContentType("application/json");
response.getWriter().write(str);
}
和我的ajax呼叫代码
$.ajax({
async: true,
url : "Servlet1",
method : "GET",
dataType : "json",
contentType: "application/json; charset=utf-8",
success : function(tableValue) {
addTable(tableValue)
}
});
现在我必须从数据库中获取数据并运行2个查询,并且必须执行两种不同的处理才能得到结果,但是现在创建新的servlet看起来并不好 我不能在Servlet中的两个方法或任意两个方法中创建一个doGet并在其中创建两个Servlet代码,这样就可以在一个servlet中编写
注意:-我不了解spring框架,所以我只想在servlet的帮助下完成
任何人都请指导我该怎么做
预先感谢
答案 0 :(得分:0)
对于HttpServlet类,没有一个好的解决方案,因为您只能有一个WITH cte AS (
-- not sure about the t2 replacement column name. I assume Video_Name here
SELECT t1.Video_Name, t2.Video_Name AS Video_Name_New
FROM [UK_Telco_Pressure_2018Q3_2019-01-31 W2] t1
INNER JOIN [UK_Telco_Pressure_2018Q3_2019-01-31 WEEK1] t2
ON t1.Updated_Campaign = t2.Updated_Campaign
)
UPDATE cte
SET Video_Name = Video_Name_New;
方法。一个不错的解决方法是在您的网址中添加一个参数,例如doGet
,然后在您的Servlet1?action=action1
中实现逻辑
该参数决定要做什么的方法。例如:
doGet()
编辑-这将是您的最终ajax调用:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
switch(action){
case "action1":
doAction1(request, response); //Method with the logic of your Servlet1 class
break;
case "action2":
doAction2(request, response);
break;
default:
throw new ServletException("Invalid action parameter");
}
}