javaweb分页的后端实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaweb分页的后端实现相关的知识,希望对你有一定的参考价值。

先上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
 

以上是关于javaweb分页的后端实现的主要内容,如果未能解决你的问题,请参考以下文章

JavaWeb分页了解一下

JAVAWEB学习笔记21_多条件查询attr和prop的区别和分页的实现

海量数据的分页怎么破

javaweb 实现分页

已经查询出来的数据如何在java页面实现分页?

项目经验前后端分离的“后端一条线”以及表格的分页的实现