java分页的实现(后台工具类和前台jsp页面)

1、首先,新建一个类Page.java

 1 public class Page implements Serializable {
 2     private static final long serialVersionUID = -3198048449643774660L;
 3     private int pageNow = 1; // 当前页数
 4     private int pageSize = 10; // 每页显示记录的条数
 5     private int totalCount; // 总记录条数
 6     private int totalPageCount; // 总页数
 7     private int startPos; // 开始位置,从0开始
 8     //构造函数,参数:总记录数和当前页
 9     public Page(int totalCount, int pageNow) {
10         this.totalCount = totalCount;
11         this.pageNow = pageNow;
12     }
13     //计算总页数,总页数=总记录数/每页显示记录的条数
14     public int getTotalPageCount() {
15         totalPageCount = getTotalCount() / getPageSize();
16         return (totalCount % pageSize == 0) ? totalPageCount : totalPageCount + 1;
17     }
18     public void setTotalPageCount(int totalPageCount) {
19         this.totalPageCount = totalPageCount;
20     }
21     public int getPageNow() {
22         return pageNow;
23     }
24     public void setPageNow(int pageNow) {
25         this.pageNow = pageNow;
26     }
27     public int getPageSize() {
28         return pageSize;
29     }
30     public void setPageSize(int pageSize) {
31         this.pageSize = pageSize;
32     }
33     public int getTotalCount() {
34         return totalCount;
35     }
36     public void setTotalCount(int totalCount) {
37         this.totalCount = totalCount;
38     }
39     //取得选择记录的初始位置
40     public int getStartPos() {
41         return (pageNow - 1) * pageSize;
42     }
43 }

2、在Dao层加入两个方法,分别获取总的记录数和每页显示的list集合,DBUtil.java是数据库工具类。

 1 // 获取总的记录数
 2 public static int getCount() throws SQLException {
 3     Connection conn = DBUtil.getConn();
 4     PreparedStatement pst = null;
 5     String sql = "select count(*) from users";
 6     pst = conn.prepareStatement(sql);
 7     ResultSet rs = pst.executeQuery();
 8     int count=0;
 9     if(rs.next()){
10         count=rs.getInt(1);
11     }
12     DBUtil.close(conn, pst, rs);
13     return count;
14 }
15 // 分页查找
16 public static ArrayList<Users> findByPage(int pos, int size) throws SQLException {
17     Connection conn = DBUtil.getConn();
18     ArrayList<Users> userList = new ArrayList<Users>();
19     PreparedStatement pst = null;
20     String sql = "select * from users limit ?,?";
21     pst = conn.prepareStatement(sql);
22     pst.setInt(1, pos);
23     pst.setInt(2, size);
24     ResultSet rs = pst.executeQuery();
25     while (rs.next()) {
26         Users user = new Users();
27         user.setUserid(rs.getInt(1));
28         user.setUsername(rs.getString(2));
29     }
30     DBUtil.close(conn, pst, rs);
31     return userList;
32 }

3、在Servlet中调用Dao层的方法,并向页面传递参数,

 1 String pageNow=request.getParameter("pageNow");//获取当前页
 2 int totalCount=UsersDao.getCount();//获取总的记录数
 3 List<Users> userList=new ArrayList<Users>();
 4 Page page=null;
 5 if(pageNow!=null){
 6     page=new Page(totalCount, Integer.parseInt(pageNow));
 7     userList=UsersDao.findByPage(page.getStartPos(), page.getPageSize());//从startPos开始,获取pageSize条数据
 8 }else{
 9     page=new Page(totalCount, 1);//初始化pageNow为1
10     userList=UsersDao.findByPage(page.getStartPos(), page.getPageSize());//从startPos开始,获取pageSize条数据
11 }
12 request.setAttribute("page", page);
13 request.setAttribute("userList", userList);
14 request.getRequestDispatcher("/WEB-INF/views/homePage.jsp").forward(request, response);

4、在jsp页面中添加如下代码:

 1 <body>
 2     <div class="page_nav">
 3         <c:choose>
 4             <c:when test="${page.totalPageCount <= 10}"><!-- 如果总页数小于10,则全部显示 -->
 5                 <c:set var="begin" value="1"></c:set>
 6                 <c:set var="end" value="${page.totalPageCount }"></c:set>
 7             </c:when>
 8             <c:when test="${page.pageNow <= 5 }"><!-- 如果总页数小于5,则显示1-10页 -->
 9                 <c:set var="begin" value="1"></c:set>
10                 <c:set var="end" value="10"></c:set>
11             </c:when>
12             <c:otherwise><!-- 否则,显示前5页和后5页,保证当前页在中间 -->
13                 <c:set var="begin" value="${page.pageNow-5 }"></c:set>
14                 <c:set var="end" value="${page.pageNow+5 }"></c:set>
15                 <c:if test="${end > page.totalPageCount }"><!-- 如果end值小于总的记录数,则显示最后10页 -->
16                     <c:set var="end" value="${page.totalPageCount}"></c:set>
17                     <c:set var="begin" value="${end-10 }"></c:set>
18                 </c:if>
19             </c:otherwise>
20         </c:choose>
21         <c:choose>
22             <c:when test="${page.pageNow != 1 }"><!-- 如果当前页为1,则不显示首页和上一页 -->
23                 <a href="?oper=login&pageNow=1">首页</a> 
24                 <a href="?oper=login&pageNow=${page.pageNow-1 }">上一页</a>
25             </c:when>
26         </c:choose>
27         <!-- 遍历页码 -->
28         <c:forEach begin="${begin }" end="${end }" var="index">
29             <c:choose>
30                 <c:when test="${page.pageNow == index }"><!-- 如果为当前页,则特殊显示 -->
31                     <a style="height:24px; margin:0 3px; border:none; background:#C00;">${index}</a>
32                 </c:when>
33                 <c:otherwise><!-- 否则,普通显示 -->
34                     <a href="?oper=login&pageNow=${index }">${index }</a>
35                 </c:otherwise>
36             </c:choose>
37         </c:forEach>
38         <c:choose>
39             <c:when test="${page.pageNow != page.totalPageCount }"><!-- 如果当前页为总的记录数,则不显示末页和下一页 -->
40                 <a href="?oper=login&pageNow=${page.pageNow+1 }">下一页</a> 
41                 <a href="?oper=login&pageNow=${page.totalPageCount }">末页</a>
42             </c:when>
43         </c:choose>
44         共${page.totalPageCount }页,${page.totalCount }条记录 到第<input
45             value="${page.pageNow }" name="pn" id="pn_input" /><input
46             id="pn_btn" type="button" value="确定">
47         <script type="text/javascript">
48             //为按钮绑定一个单击响应函数
49             $("#pn_btn").click(function() {
50                 //获取到要跳转的页码
51                 var pageNow = $("#pn_input").val();
52                 //通过修改window.location属性跳转到另一个页面
53                 window.location = "?oper=login&pageNow=" + pageNow;
54             });
55         </script>
56     </div>
57 </body>

最后附上数据库工具类代码DBUtil:

 1 package com.bwlu.common;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 
 9 public class DBUtil {
10 
11     private static String DRIVER = null;
12 
13     private static String URL = null;
14 
15     private static String USERNAME = null;
16 
17     private static String PASSWORD = null;
18 
19     static {
20         DRIVER = "com.mysql.jdbc.Driver";
21         URL = "jdbc:mysql://localhost:3306/mytest";
22         USERNAME = "root";
23         PASSWORD = "mysql";
24     }
25 
26     public static Connection getConn() {
27         Connection conn = null;
28         try {
29             /* 加载驱动 */
30 //            System.out.println(DRIVER);
31             Class.forName(DRIVER);
32             /* 获取连接 */
33             conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
34 
35         } catch (ClassNotFoundException e) {
36             e.printStackTrace();
37         } catch (SQLException e) {
38             e.printStackTrace();
39         }
40         return conn;
41     }
42 
43     // 关闭连接
44     public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
45         try {
46             if (rs != null) {
47                 rs.close();
48             }
49             if (ps != null) {
50                 ps.close();
51             }
52             if (conn != null) {
53                 conn.close();
54             }
55         } catch (SQLException e) {
56             e.printStackTrace();
57         }
58     }
59 }
DBUtil

 SSM框架中【MyBatis分页语句】

UsersMapper.java

1 public interface UsersMapper {
2     // 获取分页记录,startPos:从第几行开始获取,pageSize:获取的条数
3     List<Users> selectByPage(@Param(value = "startPos") Integer startPos,
4             @Param(value = "pageSize") Integer pageSize);
5     // 获取数据库总的记录数,返回users表中总的记录条数
6     int getCount();
7 }

UsersMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="com.bwlu.mapper.UsersMapper" >
 4   <resultMap id="BaseResultMap" type="com.bwlu.bean.Users" >
 5     <id column="userId" property="userid" jdbcType="INTEGER" />
 6     <result column="userName" property="username" jdbcType="VARCHAR" />
 7     <result column="password" property="password" jdbcType="VARCHAR" />
 8     <result column="userEmail" property="useremail" jdbcType="VARCHAR" />
 9     <result column="permission" property="permission" jdbcType="INTEGER" />
10   </resultMap>
11   
12   <!-- 分页SQL语句 -->  
13   <select id="selectByPage" resultMap="BaseResultMap">  
14       select *  from Users limit #{startPos},#{pageSize}
15   </select>  
16   <!-- 取得记录的总数 -->  
17   <select id="getCount" resultType="java.lang.Integer">
18       SELECT COUNT(*) FROM Users  
19   </select>  
20 </mapper>

 

posted @ 2017-08-14 21:49  bwlu---ed  阅读(3570)  评论(0编辑  收藏  举报