java分页技术实现详解

1.编写通用的分页工具


  1. public class PageUtil {  
  2.       
  3.     /*参数需要页面传入*/  
  4.     private Integer pageSize=10;//每页显式多少条记录  
  5.     private Integer currentPage=1;//当前页号  
  6.       
  7.     /*参数需要从数据查询*/  
  8.     private Integer allRowsAmount=0;//总记录数  
  9.     private List<?> items;//记录集合  
  10.       
  11.     /*这些参数由计算得出*/  
  12.     private Integer allPageAmount;//总页数  
  13.     private Integer currentPageStartRow=1;//当前页面的开始行  
  14.     private Integer currentPageEndRow;//当前页面的结束行  
  15.     private Integer firstPage=1;//首页的页号  
  16.     private Integer lastPage;//末页的页号  
  17.     private Integer prevPage;//上一页页号  
  18.     private Integer nextPage;//下一页页号  
  19.     private Integer startPageNum;//导航开始页号  
  20.     private Integer endPageNum;//导航结束页号  
  21.     private Integer maxPageAmount =10;//最多显示多少页  
  22.     public List<Integer> showPageNums =new ArrayList<Integer>();//要显示的页号  
  23.       
  24.     public PageUtil() {  
  25.         super();  
  26.         // TODO Auto-generated constructor stub  
  27.     }  
  28.       
  29.     /*设置当前页*/  
  30.     public void setCurrentPage(int currentPage){  
  31.         if(currentPage <1){  
  32.             this.currentPage=1;  
  33.         }else{  
  34.             this.currentPage=currentPage;  
  35.         }  
  36.     }  
  37.     /*设置每页记录数,默认10条*/  
  38.     public void setPageSize(int pageSize) {  
  39.         this.pageSize = pageSize;  
  40.     }  
  41.     /*设置总记录数*/  
  42.     public void setAllRowsAmount(int allRowsAmount) {  
  43.         this.allRowsAmount = allRowsAmount;  
  44.     }  
  45.     /*设置分页内容*/  
  46.     public void setItems(List<?> items) {  
  47.         this.items = items;  
  48.     }  
  49.     /*设置导航页数量*/  
  50.     public void setMaxPageAmount(int maxPageAmount) {  
  51.         this.maxPageAmount = maxPageAmount;  
  52.     }  
  53.       
  54.     public void calculatePage(){  
  55.         //计算总页数  
  56.         if(this.allRowsAmount % this.pageSize ==0){  
  57.             this.allPageAmount=this.allRowsAmount/this.pageSize;  
  58.         }else{  
  59.             this.allPageAmount=this.allRowsAmount/this.pageSize+1;  
  60.         }  
  61.         //设置首页  
  62.         this.firstPage=1;  
  63.         //设置末页  
  64.         this.lastPage=this.allPageAmount;  
  65.         if(this.currentPage *pageSize <allRowsAmount){  
  66.             this.currentPageEndRow =this.currentPage*pageSize;  
  67.             this.currentPageStartRow =(this.currentPage-1)*pageSize+1;  
  68.         }else{  
  69.             this.currentPageEndRow =this.allRowsAmount;  
  70.             this.currentPageStartRow =(this.allPageAmount-1)*pageSize+1;  
  71.             if(this.currentPageStartRow <0){  
  72.                 this.currentPageStartRow=0;  
  73.             }  
  74.         }  
  75.         //设置前一页  
  76.         if(this.currentPage >1){  
  77.             this.prevPage=this.currentPage-1;  
  78.         }else{  
  79.             this.prevPage=this.currentPage;  
  80.         }  
  81.         //设置下一页  
  82.         if(this.currentPage <this.lastPage){  
  83.             this.nextPage=this.currentPage+1;  
  84.         }else{  
  85.             this.nextPage=this.lastPage;  
  86.         }  
  87.         //计算数字导航页  
  88.         startPageNum =Math.max(this.currentPage-maxPageAmount/2, firstPage);  
  89.         endPageNum =Math.min(startPageNum+maxPageAmount, lastPage);  
  90.         if(endPageNum-startPageNum <maxPageAmount){  
  91.             startPageNum =Math.max(endPageNum -maxPageAmount , 1);  
  92.         }  
  93.         for(int i=startPageNum ;i<=endPageNum;i++){  
  94.             showPageNums.add(i);  
  95.         }  
  96.     }  
  97.       
  98.     //以下get方法是对外提供的方法用来获取参数值  
  99.     public Integer getPageSize() {  
  100.         return pageSize;  
  101.     }  
  102.   
  103.     public Integer getCurrentPage() {  
  104.         return currentPage;  
  105.     }  
  106.   
  107.     public Integer getAllRowsAmount() {  
  108.         return allRowsAmount;  
  109.     }  
  110.   
  111.     public List<?> getItems() {  
  112.         return items;  
  113.     }  
  114.   
  115.     public Integer getAllPageAmount() {  
  116.         return allPageAmount;  
  117.     }  
  118.   
  119.     public Integer getCurrentPageStartRow() {  
  120.         return currentPageStartRow;  
  121.     }  
  122.   
  123.     public Integer getCurrentPageEndRow() {  
  124.         return currentPageEndRow;  
  125.     }  
  126.   
  127.     public Integer getFirstPage() {  
  128.         return firstPage;  
  129.     }  
  130.   
  131.     public Integer getLastPage() {  
  132.         return lastPage;  
  133.     }  
  134.   
  135.     public Integer getPrevPage() {  
  136.         return prevPage;  
  137.     }  
  138.   
  139.     public Integer getNextPage() {  
  140.         return nextPage;  
  141.     }  
  142.   
  143.     public Integer getStartPageNum() {  
  144.         return startPageNum;  
  145.     }  
  146.   
  147.     public Integer getEndPageNum() {  
  148.         return endPageNum;  
  149.     }  
  150.   
  151.     public Integer getMaxPageAmount() {  
  152.         return maxPageAmount;  
  153.     }  
  154.   
  155.     public List<Integer> getShowPageNums() {  
  156.         return showPageNums;  
  157.     }  
  158.   
  159.     @Override  
  160.     public String toString() {  
  161.         return "PageUtil [pageSize=" + pageSize + "currentPage="  
  162.                 + currentPage + ", allRowsAmount=" + allRowsAmount + ", 每页内容items="  
  163.                 + items + ", allPageAmount=" + allPageAmount  
  164.                 + ", currentPageStartRow=" + currentPageStartRow  
  165.                 + ", currentPageEndRow=" + currentPageEndRow + "firstPage="  
  166.                 + firstPage + ", lastPage=" + lastPage + "prevPage="  
  167.                 + prevPage + ", nextPage=" + nextPage + "startPageNum="  
  168.                 + startPageNum + ", endPageNum=" + endPageNum + "maxPageAmount="  
  169.                 + maxPageAmount + ", 页号list=" + showPageNums + "]";  
  170.     }  
  171.       
  172.     public static void main(String[] args) {  
  173.         List<String> items =new ArrayList<String>();  
  174.         for(int i=0;i<10;i++){  
  175.             items.add("str"+i);  
  176.         }  
  177.         PageUtil pageUtil =new PageUtil();  
  178.         pageUtil.setCurrentPage(1);  
  179.         //pageUtil.setItems(items);  
  180.         pageUtil.setAllRowsAmount(33);  
  181.         pageUtil.calculatePage();  
  182.         System.out.println(pageUtil);  
  183.     }  
  184. }  

2.servlet+c3p0+mysql实现分页

工程目录:


环境搭建:


  1. <dependencies>  
  2.     <dependency>  
  3.       <groupId>junit</groupId>  
  4.       <artifactId>junit</artifactId>  
  5.       <version>3.8.1</version>  
  6.       <scope>test</scope>  
  7.     </dependency>  
  8.     <dependency>  
  9.       <groupId>com.mchange</groupId>  
  10.       <artifactId>c3p0</artifactId>  
  11.       <version>0.9.2.1</version>  
  12.     </dependency>  
  13.     <dependency>  
  14.       <groupId>mysql</groupId>  
  15.       <artifactId>mysql-connector-java</artifactId>  
  16.       <version>5.1.22</version>  
  17.     </dependency>  
  18.     <dependency>  
  19.       <groupId>javax.servlet</groupId>  
  20.       <artifactId>jstl</artifactId>  
  21.       <version>1.2</version>  
  22.     </dependency>  
  23. </dependencies> 

c3p0配置文件:


  1. <c3p0-config>  
  2.     <!-- 默认配置 -->  
  3.   <default-config>  
  4.     <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property>  
  5.     <property name="driverClass">com.mysql.jdbc.Driver</property>   
  6.     <property name="user">root</property>   
  7.     <property name="password"></property>   
  8.     <property name="initialPoolSize">3</property>  
  9.     <property name="maxPoolSize">6</property>  
  10.     <property name="maxIdleTime">1000</property>  
  11.   </default-config>  
  12.   <!-- 以下的配置用于个人需要再配置 -->  
  13.   <name-config name="my_config">  
  14.     <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property>  
  15.     <property name="driverClass">com.mysql.jdbc.Driver</property>   
  16.     <property name="user">root</property>   
  17.     <property name="password"></property>   
  18.     <property name="initialPoolSize">3</property>  
  19.     <property name="maxPoolSize">6</property>  
  20.     <property name="maxIdleTime">1000</property>  
  21.   </name-config>  
  22. </c3p0-config>  

使用c3p0连接池的工具类:

  1. public class DbUtil {  
  2.       
  3.      private static DataSource dataSource=null;    
  4.      static{    
  5.          dataSource=new ComboPooledDataSource();    
  6.      }    
  7.             
  8.      public static Connection getConnection(){    
  9.          try{    
  10.              return dataSource.getConnection();    
  11.          }catch(SQLException e){    
  12.              throw new RuntimeException(e);    
  13.          }    
  14.      }    
  15.             
  16.      //释放对象的连接    
  17.      public static void close(Connection conn,Statement stmt,ResultSet rs){    
  18.          if(rs !=null){    
  19.               try{    
  20.                   rs.close();    
  21.               }catch(SQLException e){    
  22.                   e.printStackTrace();    
  23.                   throw new RuntimeException(e);    
  24.               }    
  25.          }    
  26.          if(stmt !=null){    
  27.               try{    
  28.                   stmt.close();    
  29.               }catch(SQLException e){    
  30.                   e.printStackTrace();    
  31.                   throw new RuntimeException(e);    
  32.               }    
  33.             }       
  34.          if(conn !=null){    
  35.               try{    
  36.                   conn.close();    
  37.               }catch(SQLException e){    
  38.                   e.printStackTrace();    
  39.                   throw new RuntimeException(e);    
  40.               }    
  41.          }    
  42.      }  
  43.      public static void main(String[] args) throws Exception{  
  44.          String sql="select id,username,gender from myuser limit 3,10";  
  45.          Connection conn =DbUtil.getConnection();  
  46.          PreparedStatement ps =conn.prepareStatement(sql);  
  47.          ResultSet rs =ps.executeQuery();  
  48.          while(rs.next()){  
  49.              String id =rs.getString("id");  
  50.              String username =rs.getString("username");  
  51.              String gender =rs.getString("gender");  
  52.              System.out.println(id+","+username+","+gender);  
  53.          }  
  54.          DbUtil.close(conn,ps,rs);  
  55.      }  
  56. }  
dao层:主要是获取记录的总数便于计算其他值,还有就是获取每页显示的数据。


  1. public class UserDaoImpl implements IUserDao{  
  2.       
  3.     //从数据库查询记录的总条数  
  4.     public Integer getAllRowsAmount() throws Exception{  
  5.         String sql="select count(*) from myuser";  
  6.         Connection conn =DbUtil.getConnection();  
  7.         PreparedStatement pstmt =conn.prepareStatement(sql);  
  8.         ResultSet rs =pstmt.executeQuery();  
  9.         Integer allRowsAmount=0;  
  10.         if(rs.next()){  
  11.             allRowsAmount =rs.getInt("count(*)");  
  12.         }  
  13.         DbUtil.close(conn, pstmt, rs);  
  14.         return allRowsAmount;  
  15.     }  
  16.       
  17.     //通过当前页号查询条件记录  
  18.     public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception{  
  19.         String sql="select id,username,gender from myuser limit "+(currentPageStartRow-1)+","+pageSize;  
  20.         Connection conn =DbUtil.getConnection();  
  21.         PreparedStatement pstmt =conn.prepareStatement(sql);  
  22.         ResultSet rs =pstmt.executeQuery();  
  23.         List<User> list =new ArrayList<User>();  
  24.         while(rs.next()){  
  25.             User user =new User();  
  26.             user.setId(rs.getInt("id"));  
  27.             user.setUsername(rs.getString("username"));  
  28.             user.setGender(rs.getString("gender"));  
  29.             list.add(user);  
  30.         }  
  31.         DbUtil.close(conn, pstmt, rs);  
  32.         return list;  
  33.     }  
  34.     public static void main(String[] args) throws Exception {  
  35.         UserDaoImpl userDaoImpl =new UserDaoImpl();  
  36.         PageUtil pageUtil =new PageUtil();  
  37.         pageUtil.setAllRowsAmount(userDaoImpl.getAllRowsAmount());  
  38.         pageUtil.calculatePage();  
  39.         for(User user :userDaoImpl.getUserByCurrentPage(pageUtil.getStartPageNum(), pageUtil.getPageSize())){  
  40.             System.out.println(user.getId()+","+user.getUsername()+","+user.getGender());  
  41.         }  
  42.         System.out.println(userDaoImpl.getAllRowsAmount());  
  43.     }  
  44. }  

dao接口:


  1. public interface IUserDao {  
  2.   
  3.     public Integer getAllRowsAmount() throws Exception;  
  4.       
  5.     public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception;  
  6. }  

model类:

User.java:


  1. public class User {  
  2.     private int id;  
  3.     private String username;  
  4.     private String gender;  
  5.     public int getId() {  
  6.         return id;  
  7.     }  
  8.     public void setId(int id) {  
  9.         this.id = id;  
  10.     }  
  11.     public String getUsername() {  
  12.         return username;  
  13.     }  
  14.     public void setUsername(String username) {  
  15.         this.username = username;  
  16.     }  
  17.     public String getGender() {  
  18.         return gender;  
  19.     }  
  20.     public void setGender(String gender) {  
  21.         this.gender = gender;  
  22.     }  
  23. }  

页面显示的模型Page.java:


  1. public class Page {  
  2.     private Integer currentPage;  
  3.     private Integer prevPage;  
  4.     private Integer nextPage;  
  5.     private List<User> showUsers =new ArrayList<User>();  
  6.     private List<Integer> showPageNums =new ArrayList<Integer>();  
  7.     public Integer getCurrentPage() {  
  8.         return currentPage;  
  9.     }  
  10.     public void setCurrentPage(Integer currentPage) {  
  11.         this.currentPage = currentPage;  
  12.     }  
  13.     public Integer getPrevPage() {  
  14.         return prevPage;  
  15.     }  
  16.     public void setPrevPage(Integer prevPage) {  
  17.         this.prevPage = prevPage;  
  18.     }  
  19.     public Integer getNextPage() {  
  20.         return nextPage;  
  21.     }  
  22.     public void setNextPage(Integer nextPage) {  
  23.         this.nextPage = nextPage;  
  24.     }  
  25.     public List<User> getShowUsers() {  
  26.         return showUsers;  
  27.     }  
  28.     public void setShowUsers(List<User> showUsers) {  
  29.         this.showUsers = showUsers;  
  30.     }  
  31.     public List<Integer> getShowPageNums() {  
  32.         return showPageNums;  
  33.     }  
  34.     public void setShowPageNums(List<Integer> showPageNums) {  
  35.         this.showPageNums = showPageNums;  
  36.     }  
  37. }  

service层:通过页面传入当前页号数据,来查询需要的值。

UserService.java:


  1. public class UserServiceImpl implements IUserService{  
  2.       
  3.     private IUserDao userDao =new UserDaoImpl();  
  4.       
  5.     public Page pageUsers(String currentPage) throws Exception{  
  6.         int allRowsAmount =userDao.getAllRowsAmount();  
  7.         PageUtil pageUtil =new PageUtil();  
  8.         pageUtil.setAllRowsAmount(allRowsAmount);  
  9.         if(currentPage !=null){  
  10.             pageUtil.setCurrentPage(Integer.parseInt(currentPage));  
  11.         }  
  12.         pageUtil.calculatePage();  
  13.         List<User> list =userDao.getUserByCurrentPage(pageUtil.getCurrentPageStartRow(), pageUtil.getPageSize());  
  14.         Page page =new Page();  
  15.         page.setPrevPage(pageUtil.getPrevPage());  
  16.         page.setNextPage(pageUtil.getNextPage());  
  17.         page.setShowUsers(list);  
  18.         page.setShowPageNums(pageUtil.getShowPageNums());  
  19.         page.setCurrentPage(pageUtil.getCurrentPage());  
  20.         return page;  
  21.     }  
  22. }  

Service接口:

  1. public interface IUserService {  
  2.     public Page pageUsers(String currentPage) throws Exception;  
  3. }  

Controller层:

  1. public class UserController extends HttpServlet{  
  2.   
  3.     /**  
  4.      *   
  5.      */  
  6.     private static final long serialVersionUID = 1L;  
  7.     private IUserService userService =new UserServiceImpl();  
  8.     @Override  
  9.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  10.             throws ServletException, IOException {  
  11.         String currentPage =req.getParameter("currentPage");  
  12.         Page page =null;  
  13.         try {  
  14.             page =userService.pageUsers(currentPage);  
  15.         } catch (Exception e) {  
  16.             // TODO Auto-generated catch block  
  17.             e.printStackTrace();  
  18.         }   
  19.         req.setAttribute("page", page);   
  20.         req.getRequestDispatcher("/page.jsp").forward(req, resp);  
  21.     }  
  22.   
  23.     @Override  
  24.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  25.             throws ServletException, IOException {  
  26.         super.doPost(req, resp);  
  27.     }  
  28.       
  29. }  


导入jquery的js文件:


Page.jsp文件:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  8. <script type="text/javascript" src="js/jquery-2.1.3.js"></script>  
  9. <script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>  
  10. <title>分页</title>  
  11. <style type="text/css">  
  12.     a{  
  13.         font-size:14px;  
  14.         text-decoration:none;  
  15.     }  
  16.     td{  
  17.         text-align:center;  
  18.     }  
  19.     #prevPage{  
  20.         padding:6px;  
  21.         color:blue;  
  22.         width:24px;  
  23.         height:24px;  
  24.         border:1px solid #ccc;  
  25.     }  
  26.     #pageNum{  
  27.         padding-top:6px;  
  28.         padding-left:12px;  
  29.         color:blue;  
  30.         border:1px solid #ccc;  
  31.         padding-right:12px;  
  32.         padding-bottom:6px;  
  33.     }  
  34.     #nextPage{  
  35.         padding:6px;  
  36.         color:blue;  
  37.         width:24px;  
  38.         height:24px;  
  39.         border:1px solid #ccc;  
  40.     }  
  41. </style>  
  42. </head>  
  43. <body>  
  44.     <div class="container" id="pagenation" align="center">  
  45.         <table border="1" width="80%" cellpadding="5" cellspacing="0">  
  46.             <tr>  
  47.                 <th>序号</th>  
  48.                 <th>用户名</th>  
  49.                 <th>性别</th>  
  50.             </tr>  
  51.             <c:forEach items="${page.showUsers}" var="user">  
  52.                 <tr>  
  53.                     <td>${user.id}</td>  
  54.                     <td>${user.username}</td>  
  55.                     <td>${user.gender}</td>  
  56.                 </tr>  
  57.             </c:forEach>  
  58.         </table>  
  59.     </div>  
  60.     <div>  
  61.         <c:when test="${page.currentPage==1}">  
  62.             <上一页  
  63.         </c:when>  
  64.         <c:otherwise>  
  65.             <a href="http://localhost:8080/paging/user.htm?currentPage=${page.prevPage}" id="prevPage"><上一页</a>  
  66.         </c:otherwise>  
  67.         <c:forEach items="${page.showPageNums}" var="pageNum">  
  68.             <a href="http://localhost:8080/paging/user.htm?currentPage=${pageNum}" id="pageNum">${pageNum}</a>  
  69.         </c:forEach>  
  70.         <a href="http://localhost:8080/paging/user.htm?currentPage=${page.nextPage}" id="nextPage">下一页></a>  
  71.     </div>  
  72. </body>  
  73. <script type="text/javascript">  
  74.     $(function(){  
  75.         $("#prevPage").mousemove(function(){  
  76.             $("#prevPage").css("border-color","#4a86e8");  
  77.             $("#prevPage").css("background","#d5dce8");  
  78.         });  
  79.         $("#prevPage").mouseout(function(){  
  80.             $("#prevPage").css("border-color","#ccc");  
  81.             $("#prevPage").css("background","white");  
  82.         });  
  83.         $("#nextPage").mousemove(function(){  
  84.             $("#nextPage").css("border-color","#4a86e8");  
  85.             $("#nextPage").css("background","#d5dce8");  
  86.         });  
  87.         $("#nextPage").mouseout(function(){  
  88.             $("#nextPage").css("border-color","#ccc");  
  89.             $("#nextPage").css("background","white");  
  90.         });  
  91.           
  92.     });  
  93. </script>  
  94. </html>  
结果:



猜你喜欢

转载自blog.csdn.net/qq_38963960/article/details/79267845
今日推荐