码迷,mamicode.com
首页 > 编程语言 > 详细

javaweb分页的后端实现

时间:2019-03-06 11:57:07      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:size   技术   public   user   bst   img   ice   imp   mod   

先上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了,效果图为

技术图片

 

代码地址:

链接:https://pan.baidu.com/s/18ypR3uEwvGImCmDngn0ugA
提取码:ilul

 

javaweb分页的后端实现

标签:size   技术   public   user   bst   img   ice   imp   mod   

原文地址:https://www.cnblogs.com/JAYIT/p/10482373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!