GSON与servlet

我的文件夹结构:

在此处输入图像描述

Servlet的:

@WebServlet(name = "KPItoGSON", urlPatterns = {"/KPItoGSON/*"}) public class KPItoGSON extends HttpServlet { /** * Processes requests for both HTTP * GET and * POST methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { /* * TODO output your page here. You may use following sample code. */ out.println(""); out.println(""); out.println("Servlet KPItoGSON"); out.println(""); out.println(""); out.println("

Servlet KPItoGSON at " + request.getContextPath() + "

"); out.println(""); out.println(""); } finally { out.close(); } } // /** * Handles the HTTP * GET method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); Gson gson = new Gson(); HttpServletRequest req = (HttpServletRequest) request; KPIListController klc = (KPIListController) req.getSession().getAttribute("kpilist"); String json = gson.toJson(klc); Logger.getLogger(KPItoGSON.class.getName()).warning("The value is"+klc.getKPI().get(1).getUSTER()); Logger.getLogger(KPItoGSON.class.getName()).info("The json "+json); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); }

JQuery的:

 function onButtonClickOrCertainTime(){ $.get('KPItoGSON', function(responseText) { // alert(responseText); }); } 

错误:

 /GISPages/KPI/KPItoGSON 404 (Not Found) 

我正在尝试BalusC的这个例子。通过这个例子,我想从数据库中获取新的数据到javascript变量并做一些图表。 我不习惯servlet :(。使用jQuery向servlet发送请求有什么问题?因为我想要每次使用函数onButtonClickOrCertainTime从数据库使用按钮或轮询使用GSON和Servlet方式更好或者是否可以使用jstl ?

您的servlet映射在/KPItoGSON/* ,您的webapp似乎基于到目前为止提供的信息部署在上下文根上。 因此,您的servlet正在侦听http://localhost:8080/KPItoGSON

您的404错误表示已从/GISPages/KPI文件夹中的HTML页面调用servlet。 您已在$.get()指定了与路径相关的servlet URL,因此它相对于当前请求URL中的顶级文件夹(您在浏览器的地址栏中看到的URL)。 它试图通过URL http://localhost:8080/GISPages/KPI/KPItoGSON调用servlet,因此无效。 它应该通过URL http://localhost:8080/KPItoGSON调用servlet。

除了将HTML页面移动到两个文件夹之外,您可以通过在ajax请求URL中向上移动两个文件夹来修复它:

 $.get('../../KPItoGSON', function(responseText) { alert(responseText); }); 

或者使用域相对URL(以前导斜杠开头):

 $.get('/KPItoGSON', function(responseText) { alert(responseText); }); 

顺便说一句,您应该从servlet中删除 processRequest()方法。 您的JSON输出现在与一段不相关的HTML格式不正确。