先上demo图
servlet实现部分:
package servlet; import java.io.IOException; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.User; import service.UserService; @SuppressWarnings("serial") @WebServlet(urlPatterns ="/user") public class UserServlet extends HttpServlet { @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { this.doGet(req, resp); } /* /* json {"users":[{"id":1,"name":"mercy","age":22,"sex":3},{"id":2,"name":"lily","age":23,"sex":2},{"id":3,"name":"mily","age":23,"sex":3},{"id":4,"name":"lucy","age":25,"sex":3},{"id":5,"name":"john","age":24,"sex":2}],"total":6} */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) { UserService service=new UserService(); String name=req.getParameter("name"); int page=Integer.parseInt(req.getParameter("page")); int size=Integer.parseInt(req.getParameter("size")); byte sex=Byte.parseByte(req.getParameter("sex")); page=page-1; List<User> list=service.queryDataLimit(page, size, sex, name); long count=service.queryAll(sex, name); //build json StringBuilder builder=new StringBuilder("{"users":["); String results=""; if(!list.isEmpty()) { for(User u:list) { String result = "{"id":"+u.getId()+","name":"+"""+u.getName()+"""+","age":"+u.getAge()+","sex":"+u.getSex()+"},"; builder.append(result); } //get count results=builder.toString(); results=results.substring(0, results.length()-1)+"]"; results=results+","total":"+count+"}"; }else { results="{"users":[],"+""total":"+count+"}"; } System.out.println(results); try { //set cross domain resp.setHeader("Access-Control-Allow-Origin", "*"); resp.getWriter().write(results); } catch (IOException e) { e.printStackTrace(); } } }
前端的话找个分页插件就ok了(注意有的插件首页是从0开始,有的是从1开始),效果图为
代码地址:链接:https://pan.baidu.com/s/1IORoQY-lfA2PtQZROl1zmg
提取码:uuto