我工作的AJAX从我的服务器获取数据作为后端我使用的Java servlet的
现在什么问题,我面对的是:
doGet
方法url
我给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新现在不到风度做它看起来不错,我不能创建一个doGet和内部的两种方法或任何两种方法内的servlet使得两个小服务程序代码可以在oneservlet被写入
注: - 我没有Spring框架的知识,所以我想在servlet的帮助下做到这一点只
请人指导我,我怎么能做到这一点
提前致谢
没有要用到HttpServlet类的一个很好的解决方案,因为你只能有一个doGet
方法。一个体面的解决办法将在您的网址加入一个参数,例如Servlet1?action=action1
,然后在你的doGet()
方法实现逻辑来决定基于该参数做什么。例如:
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");
}
}
编辑 - 这将是你最后的Ajax调用:
$.ajax({
async: true,
url : "Servlet1?action=action1", // Here you set the parameter
method : "GET",
dataType : "json",
contentType: "application/json; charset=utf-8",
success : function(tableValue) {
addTable(tableValue)
}
});