一、分页技术
1、前端分页
前端分页:一次性从数据库读出表的所有数据一次性的返回给客户端,由前端js来控制每一页的显示,由于一次性读出所有数据并返回给客户端,如果数据量庞大,这一次的动作可能是非常消耗服务器资源和带宽的,但是返回给客户端以后就非常轻松了,客户端在一段时间内不会再像服务器端请求资源。
2、后端分页
本文分页是后端分页实现的一种。
后端分页:由后端程序控制,每一次只返回一页大小的数据,返回并显示到客户端,优点的话就是减少单次查询数据库的时间,后端分页的方法需要频繁和服务器端进行交互,因为频繁交互,所以会给服务器带来负担。
二、实现分页
1、准备工作
在制作分页之前,首先需要了解,分页的属性有哪些?
当前页数 currentPage
总页数 totalPage
总记录数 totalSize
每页记录数 pageSize
当前页数据 pageList
等等…
我们可以将这些属性变成一个JavaBean中的属性来调用,并且实现一些分页相关的业务逻辑。
封装关于页数的数据:
请求数据: 当前页数 currentPage
响应数据: PageBean 类封装(包含上面我们说过的属性)
总页数 = (总记录数 % 每页记录数 == 0) ? (总记录数 / 每页记录数) : (总记录数 / 每页记录数 + 1);
当前页数据 list = query( select * from limit 每页记录数*(当前页数-1), 每页记录数 );
2、效果图
3、核心代码
bean PageBean.java
package com.sun.bean; import com.sun.util.DBConnection; import com.sun.util.Date_String; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * @author JumperSun * @date 2022-11-15-8:31 */ public class PageBean<T> { private Integer currentPage; // 当前页数 private Integer totalPage; // 总页数 private Integer totalSize; // 总记录数 private Integer pageSize; // 每页记录数 private List<T> list; // 当前页数据 <T> public Integer getCurrentPage() { return currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } public Integer getTotalPage() { return totalPage; } public void setTotalPage(Integer totalPage) { this.totalPage = totalPage; } public Integer getTotalSize() { return totalSize; } public void setTotalSize(Integer totalSize) { this.totalSize = totalSize; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } // 分页总数 public int size()throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = DBConnection.getConnection(); String sql = "select count(*) from user"; st = conn.createStatement(); rs = st.executeQuery(sql); if(rs.next()) { return rs.getInt(1); } } finally { DBConnection.close(rs, st, conn); } return 0; } // 分页查询数据 public List<UserBean> queryAllByLimit(int offset, int limit) throws SQLException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; List<UserBean> users=new ArrayList<UserBean>(); try { conn = DBConnection.getConnection(); String sql = "select * from user limit " + offset + "," + limit; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()==true){ UserBean tmp=new UserBean(); tmp.setUserid(rs.getInt("id")); tmp.setUsername(rs.getString("name")); tmp.setPassword(rs.getString("password")); tmp.setSex(rs.getString("sex")); tmp.setAge(rs.getInt("age")); String birthday= Date_String.getStringDate1(rs.getDate("birthday")); tmp.setBirthday(birthday); users.add(tmp); } } finally { DBConnection.close(rs, ps, conn); } return users; } // 分页查询处理 public void selectUserListByPage(Integer currentPage, PageBean<UserBean> pageBean) throws SQLException { // 当前页数 pageBean.setCurrentPage(currentPage); // 总记录数 Integer totalSize = pageBean.size(); pageBean.setTotalSize(totalSize); // 每页记录数 Integer pageSize = 3; pageBean.setPageSize(pageSize); // 总页数(没余数为整页,有余数页数+1) Integer totalPages = null; if (totalSize != null) { totalPages = (totalSize%pageSize==0) ? (totalSize/pageSize) : (totalSize/pageSize+1); } if(totalPages != null) { pageBean.setTotalPage(totalPages); } // 当前页数据 List<UserBean> list = queryAllByLimit(pageSize*(currentPage-1), pageSize); pageBean.setList(list); } }
Servlet GetUserListByPage.java
package com.sun.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.bean.PageBean; import com.sun.bean.UserBean; @WebServlet("/getUserListByPage") public class GetUserListByPage extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String currentPageStr = request.getParameter("currentPage"); Integer currentPageNum = getCurrentPage(currentPageStr); PageBean<UserBean> pageBean = new PageBean<>(); try { pageBean.selectUserListByPage(currentPageNum,pageBean); } catch (SQLException e) { e.printStackTrace(); } request.setAttribute("pageBean", pageBean); request.getRequestDispatcher("/Main.jsp").forward(request,response); } private Integer getCurrentPage(String currentPagestr) { if (null == currentPagestr) { currentPagestr = "1"; } return Integer.valueOf(currentPagestr); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
jsp Main.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" errorPage="../error.jsp" %> <%@ page import="java.util.List" %> <%@ page import="com.sun.bean.UserBean" %> <%@ page import="com.sun.bean.PageBean" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/style.css"/> <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/common.css"/> </head> <body> <div class="content"> <jsp:useBean id="pageBean" class="com.sun.bean.PageBean" scope="request"/> <table class="mtable2"> <h3 style="margin-bottom: 0">学生列表</h3> <form action="${pageContext.request.contextPath}/getUserListByPageLike" method="post"> 学生名:<input type="text" name="username" value="${param.username}"/> 性别:<input type="text" name="sex" value="${param.sex}"/> <input type="submit" value="查询"/> <input type="reset" value="重置"> </form> <tr> <th>学生id</th> <th>学生名</th> <th>密码</th> <th>性别</th> <th>年龄</th> <th>出生日期</th> <th>操作</th> </tr> <c:forEach items="${pageBean.list}" var="user"> <tr> <td>${user.getUserid()}</td> <td>${user.getUsername()}</td> <td>${user.getPassword()} </td> <td>${user.getSex()} </td> <td>${user.getAge()} </td> <td>${user.getBirthday()} </td> <td> <a href="user/UpdateUser.jsp?userid=${user.getUserid()}">修改</a> <a href="user/DelUser_do.jsp?userid=${user.getUserid()}">删除</a> </td> </tr> </c:forEach> </table> <div class="fenye"> 第${pageBean.currentPage}/${pageBean.totalPage}页 总记录数:${pageBean.totalSize}条 每页${pageBean.pageSize}条 <c:if test="${pageBean.currentPage != 1}"> <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=1"> [首页] </a> <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=${pageBean.currentPage-1}"> [上一页] </a> </c:if> <c:if test="${pageBean.currentPage != pageBean.totalPage}"> <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=${pageBean.currentPage+1}"> [下一页] </a> <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=${pageBean.totalPage}"> [尾页] </a> </c:if> </div> </div> </body> </html>
此致,一个分页就写完了。