Servlet+jsp的分頁案例


查詢的分頁,在web中經常用到。一般,分頁要維護的信息很多,我們把這些相關的信息,分裝到一個類中,PageBean。具體如下:

 1 package cn.itcast.utils;
 2 
 3 import java.util.List;
 4 
 5 import cn.itcast.entity.Employee;
 6 
 7 /**
 8  * 封裝分頁的參數
 9  * 
10  * @author Jie.Yuan
11  * 
12  */
13 public class PageBean<T> {
14     private int currentPage = 1; // 當前頁, 默認顯示第一頁
15     private int pageCount = 4;   // 每頁顯示的行數(查詢返回的行數), 默認每頁顯示4行
16     private int totalCount;      // 總記錄數
17     private int totalPage;       // 總頁數 = 總記錄數 / 每頁顯示的行數  (+ 1)
18     private List<T> pageData;       // 分頁查詢到的數據
19     
20     // 返回總頁數
21     public int getTotalPage() {
22         if (totalCount % pageCount == 0) {
23             totalPage = totalCount / pageCount;
24         } else {
25             totalPage = totalCount / pageCount + 1;
26         }
27         return totalPage;
28     }
29     public void setTotalPage(int totalPage) {
30         this.totalPage = totalPage;
31     }
32     
33     public int getCurrentPage() {
34         return currentPage;
35     }
36     public void setCurrentPage(int currentPage) {
37         this.currentPage = currentPage;
38     }
39     public int getPageCount() {
40         return pageCount;
41     }
42     public void setPageCount(int pageCount) {
43         this.pageCount = pageCount;
44     }
45     public int getTotalCount() {
46         return totalCount;
47     }
48     public void setTotalCount(int totalCount) {
49         this.totalCount = totalCount;
50     }
51     
52     public List<T> getPageData() {
53         return pageData;
54     }
55     public void setPageData(List<T> pageData) {
56         this.pageData = pageData;
57     }
58     
59     
60 
61 }

 

我們在servlet層實現數據的查詢。一般的做法是這樣的,我們在servlet中維護一個pageBean的實例,在servlet中調用查詢,並把pageBean作為參數傳入。當查詢結束后,pageBean的參數已經是查詢后的記過,servlet再把查詢后的結果,也就是封裝在pageBean中的信息保存到域中發送到jsp頁面。下面是servlet中的內容:

 1 /**
 2  * 4. 控制層開發
 3  * @author Jie.Yuan
 4  *
 5  */
 6 public class IndexServlet extends HttpServlet {
 7     // 創建Service實例
 8     private IEmployeeService employeeService = new EmployeeService();
 9     // 跳轉資源
10     private String uri;
11 
12     public void doGet(HttpServletRequest request, HttpServletResponse response)
13             throws ServletException, IOException {
14         
15         try {
16             //1. 獲取“當前頁”參數;  (第一次訪問當前頁為null) 
17             String currPage = request.getParameter("currentPage");
18             // 判斷
19             if (currPage == null || "".equals(currPage.trim())){
20                 currPage = "1";      // 第一次訪問,設置當前頁為1;
21             }
22             // 轉換
23             int currentPage = Integer.parseInt(currPage);
24             
25             //2. 創建PageBean對象,設置當前頁參數; 傳入service方法參數
26             PageBean<Employee> pageBean = new PageBean<Employee>();
27             pageBean.setCurrentPage(currentPage);
28             
29             //3. 調用service  
30             employeeService.getAll(pageBean);    // 【pageBean已經被dao填充了數據】
31             
32             //4. 保存pageBean對象,到request域中
33             request.setAttribute("pageBean", pageBean);
34             
35             //5. 跳轉 
36             uri = "/WEB-INF/list.jsp";
37         } catch (Exception e) {
38             e.printStackTrace();  // 測試使用
39             // 出現錯誤,跳轉到錯誤頁面;給用戶友好提示
40             uri = "/error/error.jsp";
41         }
42         request.getRequestDispatcher(uri).forward(request, response);
43         
44     }
45 
46     public void doPost(HttpServletRequest request, HttpServletResponse response)
47             throws ServletException, IOException {
48         this.doGet(request, response);
49     }
50 
51 }

下面是dao層查詢的內容:

 1 /**
 2  * 2. 數據訪問層實現
 3  * @author Jie.Yuan
 4  *
 5  */
 6 public class EmployeeDao implements IEmployeeDao {
 7 
 8     @Override
 9     public void getAll(PageBean<Employee> pb) {
10         
11         //2. 查詢總記錄數;  設置到pb對象中
12         int totalCount = this.getTotalCount();
13         pb.setTotalCount(totalCount);
14         
15         /*
16          * 問題: jsp頁面,如果當前頁為首頁,再點擊上一頁報錯!
17          *              如果當前頁為末頁,再點下一頁顯示有問題!
18          * 解決:
19          *        1. 如果當前頁 <= 0;       當前頁設置當前頁為1;
20          *        2. 如果當前頁 > 最大頁數;  當前頁設置為最大頁數
21          */
22         // 判斷
23         if (pb.getCurrentPage() <=0) {
24             pb.setCurrentPage(1);                        // 把當前頁設置為1
25         } else if (pb.getCurrentPage() > pb.getTotalPage()){
26             pb.setCurrentPage(pb.getTotalPage());        // 把當前頁設置為最大頁數
27         }
28         
29         //1. 獲取當前頁: 計算查詢的起始行、返回的行數
30         int currentPage = pb.getCurrentPage();
31         int index = (currentPage -1 ) * pb.getPageCount();        // 查詢的起始行
32         int count = pb.getPageCount();                            // 查詢返回的行數
33         
34         
35         //3. 分頁查詢數據;  把查詢到的數據設置到pb對象中
36         String sql = "select * from employee limit ?,?";
37         
38         try {
39             // 得到Queryrunner對象
40             QueryRunner qr = JdbcUtils.getQueryRuner();
41             // 根據當前頁,查詢當前頁數據(一頁數據)
42             List<Employee> pageData = qr.query(sql, new BeanListHandler<Employee>(Employee.class), index, count);
43             // 設置到pb對象中
44             pb.setPageData(pageData);
45             
46         } catch (Exception e) {
47             throw new RuntimeException(e);
48         }
49         
50     }
51 
52     @Override
53     public int getTotalCount() {
54         String sql = "select count(*) from employee";
55         try {
56             // 創建QueryRunner對象
57             QueryRunner qr = JdbcUtils.getQueryRuner();
58             // 執行查詢, 返回結果的第一行的第一列
59             Long count = qr.query(sql, new ScalarHandler<Long>());
60             return count.intValue();
61         } catch (Exception e) {
62             throw new RuntimeException(e);
63         }
64     }
65 
66 }

最后jsp頁面吧查詢的結果,從域中拿出來展示:

 1  <body>
 2       <table border="1" width="80%" align="center" cellpadding="5" cellspacing="0">
 3           <tr>
 4               <td>序號</td>
 5               <td>員工編號</td>
 6               <td>員工姓名</td>
 7           </tr>
 8           <!-- 迭代數據 -->
 9           <c:choose>
10               <c:when test="${not empty requestScope.pageBean.pageData}">
11                   <c:forEach var="emp" items="${requestScope.pageBean.pageData}" varStatus="vs">
12                       <tr>
13                           <td>${vs.count }</td>
14                           <td>${emp.empId }</td>
15                           <td>${emp.empName }</td>
16                       </tr>
17                   </c:forEach>
18               </c:when>
19               <c:otherwise>
20                   <tr>
21                       <td colspan="3">對不起,沒有你要找的數據</td>
22                   </tr>
23               </c:otherwise>
24           </c:choose>
25           
26           <tr>
27               <td colspan="3" align="center">
28                   當前${requestScope.pageBean.currentPage }/${requestScope.pageBean.totalPage }頁     &nbsp;&nbsp;
29                   
30                   <a href="${pageContext.request.contextPath }/index?currentPage=1">首頁</a>
31                   <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage-1}">上一頁 </a>
32                   <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage+1}">下一頁 </a>
33                   <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.totalPage}">末頁</a>
34               </td>
35           </tr>
36           
37       </table>
38   </body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM