✅✅作者主页:🔗孙不坚1208的博客
🔥🔥精选专栏:🔗JavaWeb从入门到精通(持续更新中)
📋📋 本文摘要:本篇文章主要分享如何使用Servlet+JSP+JavaBean写一个分页。💞💞觉得文章还不错的话欢迎大家点赞👍➕收藏⭐️➕评论💬支持博主🤞
👉 👉你的一键三连是我更新的最大动力❤️❤️
手写分页总结
运行环境:tomcat8.0+idea
技术:servlet+jsp+javabean+mysql
一、分页技术
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
packagecom.sun.bean;importcom.sun.util.DBConnection;importcom.sun.util.Date_String;importjava.sql.*;importjava.util.ArrayList;importjava.util.List;/**
* @author JumperSun
* @date 2022-11-15-8:31
*/publicclassPageBean<T>{privateInteger currentPage;// 当前页数privateInteger totalPage;// 总页数privateInteger totalSize;// 总记录数privateInteger pageSize;// 每页记录数privateList<T> list;// 当前页数据 <T>publicIntegergetCurrentPage(){return currentPage;}publicvoidsetCurrentPage(Integer currentPage){this.currentPage = currentPage;}publicIntegergetTotalPage(){return totalPage;}publicvoidsetTotalPage(Integer totalPage){this.totalPage = totalPage;}publicIntegergetTotalSize(){return totalSize;}publicvoidsetTotalSize(Integer totalSize){this.totalSize = totalSize;}publicIntegergetPageSize(){return pageSize;}publicvoidsetPageSize(Integer pageSize){this.pageSize = pageSize;}publicList<T>getList(){return list;}publicvoidsetList(List<T> list){this.list = list;}// 分页总数publicintsize()throwsSQLException{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);}return0;}// 分页查询数据publicList<UserBean>queryAllByLimit(int offset,int limit)throwsSQLException{Connection conn =null;PreparedStatement ps =null;ResultSet rs =null;List<UserBean> users=newArrayList<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=newUserBean();
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;}// 分页查询处理publicvoidselectUserListByPage(Integer currentPage,PageBean<UserBean> pageBean)throwsSQLException{// 当前页数
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
packagecom.sun.servlet;importjava.io.IOException;importjava.sql.SQLException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.sun.bean.PageBean;importcom.sun.bean.UserBean;@WebServlet("/getUserListByPage")publicclassGetUserListByPageextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{String currentPageStr = request.getParameter("currentPage");Integer currentPageNum =getCurrentPage(currentPageStr);PageBean<UserBean> pageBean =newPageBean<>();try{
pageBean.selectUserListByPage(currentPageNum,pageBean);}catch(SQLException e){
e.printStackTrace();}
request.setAttribute("pageBean", pageBean);
request.getRequestDispatcher("/Main.jsp").forward(request,response);}privateIntegergetCurrentPage(String currentPagestr){if(null== currentPagestr){
currentPagestr ="1";}returnInteger.valueOf(currentPagestr);}@OverrideprotectedvoiddoPost(HttpServletRequest request,HttpServletResponse response)throwsServletException,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>
此致,一个分页就写完了。
版权归原作者 請你喝杯Java 所有, 如有侵权,请联系我们删除。