Front-end JSP page:
<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% string Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; %> <! Doctype HTML>
A servlet in the background obtains data from MySQL and processes it as a jsonarray
package com.action;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class JsonServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { Toto toto = new Toto();toto.selectAllUsers();JSONArray json = JSONArray.fromObject(toto.getUsers()); response.setCharacterEncoding("utf-8");PrintWriter pw = response.getWriter();pw.print(json);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
Effect after running:
Additional: You can write jquery asynchronous data retrieval as follows: (this method is recommended, which is relatively standard)
$.getJSON("servlet/JsonServlet",function(htmlobj){ $(".sj").empty(); var html = '<table>'; $.each(htmlobj,function(entryIndex,entry){ html += '<tr><td>'+entry['id']+'</td></tr>'; }); html += '</table>'; $(".sj").append(html); });}
You can also write as follows:
$.ajax({url:'servlet/JsonServlet',type:'post',success:function(msg){var htmlobj = jQuery.parseJSON(msg);var html = '<table>';$.each(htmlobj,function(entryIndex,entry){ html += '<tr><td>'+entry['id']+'</td></tr>'; });html += '</table>'; $(".sj").html(html); }});