其实就是把数据库中的数据查询出来拼接成一个Json数据
1 import dao.UserDao; 2 import endy.User; 3 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.io.IOException; 10 import java.io.PrintWriter; 11 import java.util.List; 12 13 @WebServlet("/Json") 14 public class Json extends HttpServlet { 15 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 16 17 } 18 19 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 20 UserDao ud=new UserDao(); 21 List<User> users=ud.FandAll(); 22 response.setCharacterEncoding("utf-8"); 23 response.setContentType("application/json;charset=utf-8"); 24 PrintWriter out=response.getWriter(); 25 String[] keys={"id","name","pwd","phone","img"};//属性名称 26 StringBuffer json=new StringBuffer("["); 27 for (int i=0;i<users.size();i++){ 28 json.append("{"); 29 User u=users.get(i); 30 Object[] values=u.toarry(); 31 for (int j=0;j<keys.length;j++){ 32 json.append("""+keys[j]+"":""+values[j]+"""); 33 if (j<keys.length-1) json.append(","); 34 } 35 json.append("}"); 36 if (i<users.size()-1) json.append(","); 37 } 38 json.append("]"); 39 out.write(json.toString()); 40 out.close(); 41 } 42 }
这里是后台直接拼成json字符串
26 StringBuffer json=new StringBuffer("[");
27 for (int i=0;i<users.size();i++){
28 json.append("{");
29 User u=users.get(i);
30 Object[] values=u.toarry();
31 for (int j=0;j<keys.length;j++){
32 json.append("""+keys[j]+"":""+values[j]+""");
33 if (j<keys.length-1) json.append(",");
34 }
35 json.append("}");
36 if (i<users.size()-1) json.append(",");
37 }
38 json.append("]");