我的文件夹结构:
小服务程序:
@WebServlet(name = "KPItoGSON", urlPatterns = {"/KPItoGSON/*"})
public class KPItoGSON extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> 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("<html>");
out.println("<head>");
out.println("<title>Servlet KPItoGSON</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet KPItoGSON at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> 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);
}
查询:
function onButtonClickOrCertainTime(){
$.get('KPItoGSON', function(responseText) { //
alert(responseText);
});
}
错误:
/GISPages/KPI/KPItoGSON 404 (Not Found)
我正在尝试BalusC 的这个例子。通过这个例子,我想从数据库中获取新数据到 javascript 变量中并做一些图表。我不习惯 servlet :(。使用 jQuery 向 servlet 发送请求有什么问题?因为我每次按钮或使用数据库中的函数onButtonClickOrCertainTime 进行轮询时都想要新数据,所以使用 GSON 和 Servlet 方式更好,或者使用jstl ?