Java分页

本文介绍了一种通用的分页工具类PageUtil的设计与实现,并结合Servlet、C3P0及MySQL展示了如何搭建环境实现分页功能。该工具类支持自定义每页显示条目数、导航页数量等,并提供了计算总页数、前后页等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.编写通用的分页工具public class PageUtil { /*参数需要页面传入*/ private Integer pageSize=10;//每页显式多少条记录 private Integer currentPage=1;//当前页号 /*参数需要从数据查询*/ private Integer allRowsAmount=0;//总记录数 private List<?> items;//记录集合 /*这些参数由计算得出*/ private Integer allPageAmount;//总页数 private Integer currentPageStartRow=1;//当前页面的开始行 private Integer currentPageEndRow;//当前页面的结束行 private Integer firstPage=1;//首页的页号 private Integer lastPage;//末页的页号 private Integer prevPage;//上一页页号 private Integer nextPage;//下一页页号 private Integer startPageNum;//导航开始页号 private Integer endPageNum;//导航结束页号 private Integer maxPageAmount =10;//最多显示多少页 public List<Integer> showPageNums =new ArrayList<Integer>();//要显示的页号 public PageUtil() { super(); // TODO Auto-generated constructor stub } /*设置当前页*/ public void setCurrentPage(int currentPage){ if(currentPage <1){ this.currentPage=1; }else{ this.currentPage=currentPage; } } /*设置每页记录数,默认10条*/ public void setPageSize(int pageSize) { this.pageSize = pageSize; } /*设置总记录数*/ public void setAllRowsAmount(int allRowsAmount) { this.allRowsAmount = allRowsAmount; } /*设置分页内容*/ public void setItems(List<?> items) { this.items = items; } /*设置导航页数量*/ public void setMaxPageAmount(int maxPageAmount) { this.maxPageAmount = maxPageAmount; } public void calculatePage(){ //计算总页数 if(this.allRowsAmount % this.pageSize ==0){ this.allPageAmount=this.allRowsAmount/this.pageSize; }else{ this.allPageAmount=this.allRowsAmount/this.pageSize+1; } //设置首页 this.firstPage=1; //设置末页 this.lastPage=this.allPageAmount; if(this.currentPage *pageSize <allRowsAmount){ this.currentPageEndRow =this.currentPage*pageSize; this.currentPageStartRow =(this.currentPage-1)*pageSize+1; }else{ this.currentPageEndRow =this.allRowsAmount; this.currentPageStartRow =(this.allPageAmount-1)*pageSize+1; if(this.currentPageStartRow <0){ this.currentPageStartRow=0; } } //设置前一页 if(this.currentPage >1){ this.prevPage=this.currentPage-1; }else{ this.prevPage=this.currentPage; } //设置下一页 if(this.currentPage <this.lastPage){ this.nextPage=this.currentPage+1; }else{ this.nextPage=this.lastPage; } //计算数字导航页 startPageNum =Math.max(this.currentPage-maxPageAmount/2, firstPage); endPageNum =Math.min(startPageNum+maxPageAmount, lastPage); if(endPageNum-startPageNum <maxPageAmount){ startPageNum =Math.max(endPageNum -maxPageAmount , 1); } for(int i=startPageNum ;i<=endPageNum;i++){ showPageNums.add(i); } } //以下get方法是对外提供的方法用来获取参数值 public Integer getPageSize() { return pageSize; } public Integer getCurrentPage() { return currentPage; } public Integer getAllRowsAmount() { return allRowsAmount; } public List<?> getItems() { return items; } public Integer getAllPageAmount() { return allPageAmount; } public Integer getCurrentPageStartRow() { return currentPageStartRow; } public Integer getCurrentPageEndRow() { return currentPageEndRow; } public Integer getFirstPage() { return firstPage; } public Integer getLastPage() { return lastPage; } public Integer getPrevPage() { return prevPage; } public Integer getNextPage() { return nextPage; } public Integer getStartPageNum() { return startPageNum; } public Integer getEndPageNum() { return endPageNum; } public Integer getMaxPageAmount() { return maxPageAmount; } public List<Integer> getShowPageNums() { return showPageNums; } @Override public String toString() { return "PageUtil [pageSize=" + pageSize + ", currentPage=" + currentPage + ", allRowsAmount=" + allRowsAmount + ", 每页内容items=" + items + ", allPageAmount=" + allPageAmount + ", currentPageStartRow=" + currentPageStartRow + ", currentPageEndRow=" + currentPageEndRow + ", firstPage=" + firstPage + ", lastPage=" + lastPage + ", prevPage=" + prevPage + ", nextPage=" + nextPage + ", startPageNum=" + startPageNum + ", endPageNum=" + endPageNum + ", maxPageAmount=" + maxPageAmount + ", 页号list=" + showPageNums + "]"; } public static void main(String[] args) { List<String> items =new ArrayList<String>(); for(int i=0;i<10;i++){ items.add("str"+i); } PageUtil pageUtil =new PageUtil(); pageUtil.setCurrentPage(1); //pageUtil.setItems(items); pageUtil.setAllRowsAmount(33); pageUtil.calculatePage(); System.out.println(pageUtil); } } 2.servlet+c3p0+mysql实现分页环境搭建:<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.2.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.22</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> c3p0配置文件:<c3p0-config> <!-- 默认配置 --> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password"></property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </default-config> <!-- 以下的配置用于个人需要再配置 --> <name-config name="my_config"> <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password"></property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </name-config> </c3p0-config> 使用c3p0连接池的工具类:public class DbUtil { private static DataSource dataSource=null; static{ dataSource=new ComboPooledDataSource(); } public static Connection getConnection(){ try{ return dataSource.getConnection(); }catch(SQLException e){ throw new RuntimeException(e); } } //释放对象的连接 public static void close(Connection conn,Statement stmt,ResultSet rs){ if(rs !=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } if(stmt !=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } if(conn !=null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } } public static void main(String[] args) throws Exception{ String sql="select id,username,gender from myuser limit 3,10"; Connection conn =DbUtil.getConnection(); PreparedStatement ps =conn.prepareStatement(sql); ResultSet rs =ps.executeQuery(); while(rs.next()){ String id =rs.getString("id"); String username =rs.getString("username"); String gender =rs.getString("gender"); System.out.println(id+","+username+","+gender); } DbUtil.close(conn,ps,rs); } } dao层:主要是获取记录的总数便于计算其他值,还有就是获取每页显示的数据。public class UserDaoImpl implements IUserDao{ //从数据库查询记录的总条数 public Integer getAllRowsAmount() throws Exception{ String sql="select count(*) from myuser"; Connection conn =DbUtil.getConnection(); PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs =pstmt.executeQuery(); Integer allRowsAmount=0; if(rs.next()){ allRowsAmount =rs.getInt("count(*)"); } DbUtil.close(conn, pstmt, rs); return allRowsAmount; } //通过当前页号查询条件记录 public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception{ String sql="select id,username,gender from myuser limit "+(currentPageStartRow-1)+","+pageSize; Connection conn =DbUtil.getConnection(); PreparedStatement pstmt =conn.prepareStatement(sql); ResultSet rs =pstmt.executeQuery(); List<User> list =new ArrayList<User>(); while(rs.next()){ User user =new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setGender(rs.getString("gender")); list.add(user); } DbUtil.close(conn, pstmt, rs); return list; } public static void main(String[] args) throws Exception { UserDaoImpl userDaoImpl =new UserDaoImpl(); PageUtil pageUtil =new PageUtil(); pageUtil.setAllRowsAmount(userDaoImpl.getAllRowsAmount()); pageUtil.calculatePage(); for(User user :userDaoImpl.getUserByCurrentPage(pageUtil.getStartPageNum(), pageUtil.getPageSize())){ System.out.println(user.getId()+","+user.getUsername()+","+user.getGender()); } System.out.println(userDaoImpl.getAllRowsAmount()); } } dao接口:public interface IUserDao { public Integer getAllRowsAmount() throws Exception; public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception; } model类:User.java:[html] view plain copypublic class User { private int id; private String username; private String gender; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } } 页面显示的模型Page.java:public class Page { private Integer currentPage; private Integer prevPage; private Integer nextPage; private List<User> showUsers =new ArrayList<User>(); private List<Integer> showPageNums =new ArrayList<Integer>(); public Integer getCurrentPage() { return currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } public Integer getPrevPage() { return prevPage; } public void setPrevPage(Integer prevPage) { this.prevPage = prevPage; } public Integer getNextPage() { return nextPage; } public void setNextPage(Integer nextPage) { this.nextPage = nextPage; } public List<User> getShowUsers() { return showUsers; } public void setShowUsers(List<User> showUsers) { this.showUsers = showUsers; } public List<Integer> getShowPageNums() { return showPageNums; } public void setShowPageNums(List<Integer> showPageNums) { this.showPageNums = showPageNums; } } service层:通过页面传入当前页号数据,来查询需要的值。UserService.java:public class UserServiceImpl implements IUserService{ private IUserDao userDao =new UserDaoImpl(); public Page pageUsers(String currentPage) throws Exception{ int allRowsAmount =userDao.getAllRowsAmount(); PageUtil pageUtil =new PageUtil(); pageUtil.setAllRowsAmount(allRowsAmount); if(currentPage !=null){ pageUtil.setCurrentPage(Integer.parseInt(currentPage)); } pageUtil.calculatePage(); List<User> list =userDao.getUserByCurrentPage(pageUtil.getCurrentPageStartRow(), pageUtil.getPageSize()); Page page =new Page(); page.setPrevPage(pageUtil.getPrevPage()); page.setNextPage(pageUtil.getNextPage()); page.setShowUsers(list); page.setShowPageNums(pageUtil.getShowPageNums()); page.setCurrentPage(pageUtil.getCurrentPage()); return page; } } Service接口:[html] view plain copypublic interface IUserService { public Page pageUsers(String currentPage) throws Exception; } Controller层:public class UserController extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; private IUserService userService =new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String currentPage =req.getParameter("currentPage"); Page page =null; try { page =userService.pageUsers(currentPage); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } req.setAttribute("page", page); req.getRequestDispatcher("/page.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } } 导入jquery的js文件:Page.jsp文件:[html] view plain copy<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!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"> <script type="text/javascript" src="js/jquery-2.1.3.js"></script> <script type="text/javascript" src="js/jquery-2.1.3.min.js"></script> <title>分页</title> <style type="text/css"> a{ font-size:14px; text-decoration:none; } td{ text-align:center; } #prevPage{ padding:6px; color:blue; width:24px; height:24px; border:1px solid #ccc; } #pageNum{ padding-top:6px; padding-left:12px; color:blue; border:1px solid #ccc; padding-right:12px; padding-bottom:6px; } #nextPage{ padding:6px; color:blue; width:24px; height:24px; border:1px solid #ccc; } </style> </head> <body> <div class="container" id="pagenation" align="center"> <table border="1" width="80%" cellpadding="5" cellspacing="0"> <tr> <th>序号</th> <th>用户名</th> <th>性别</th> </tr> <c:forEach items="${page.showUsers}" var="user"> <tr> <td>${user.id}</td> <td>${user.username}</td> <td>${user.gender}</td> </tr> </c:forEach> </table> </div> <div> <c:when test="${page.currentPage==1}"> <上一页 </c:when> <c:otherwise> <a href="http://localhost:8080/paging/user.htm?currentPage=${page.prevPage}" id="prevPage"><上一页</a> </c:otherwise> <c:forEach items="${page.showPageNums}" var="pageNum"> <a href="http://localhost:8080/paging/user.htm?currentPage=${pageNum}" id="pageNum">${pageNum}</a> </c:forEach> <a href="http://localhost:8080/paging/user.htm?currentPage=${page.nextPage}" id="nextPage">下一页></a> </div> </body> <script type="text/javascript"> $(function(){ $("#prevPage").mousemove(function(){ $("#prevPage").css("border-color","#4a86e8"); $("#prevPage").css("background","#d5dce8"); }); $("#prevPage").mouseout(function(){ $("#prevPage").css("border-color","#ccc"); $("#prevPage").css("background","white"); }); $("#nextPage").mousemove(function(){ $("#nextPage").css("border-color","#4a86e8"); $("#nextPage").css("background","#d5dce8"); }); $("#nextPage").mouseout(function(){ $("#nextPage").css("border-color","#ccc"); $("#nextPage").css("background","white"); }); }); </script> </html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值