1. 程式人生 > >Java實現分頁展示

Java實現分頁展示

一、為什麼我們要使用分頁展示資訊

   當我們的需要展示的資料比較多時,這樣在我們查詢的資料的量也會增加,給資料庫的壓力還是比較大的,查詢時間也會增加;並且在頁面的顯示的資料也因為顯示的資料太多導致不容易使得使用者檢視,這時我們就會想到讓使用者方便又能夠減輕資料庫的壓力

二、實現分頁的首要條件

  這裡我們使用的是servlet和jsp來實現,所以我們介紹的時候也是簡單分開介紹一下這兩部分

三、分析

  (1)要實現顯示內容分頁,首先你要有一些先知條件:當前頁數(currentPage)、每頁顯示的資料的數量(pageCount),以及每頁顯示的頁的連線個數(我們一般就是顯示當前頁數的-2 到 當前頁數 + 2 的範圍)。

  (2)然後通過資料庫可以查詢:一共有多少條資料(totalCount)  

             select count (*) from table_name ;

          進而得到一共可以分多少頁totalPage

    根據這個三個一直條件,我們可以在資料使用limit來進行分頁查詢List<Entity> pageData

            select * from table_name limit currentPage , pageCount;

(3)通過totalCount和totalPage,可以算出來要在頁顯示哪些頁連結:開始(start = currentPage - 2)和結束(end = currentPage + 2)

      如果剛開始就給定了start和end,可能會出現這種情況,start < 1 和 end < totalPage的情況,不在顯示範圍之內,所以我們要在這裡設定一下

//分頁現實的頁數
		this.start = 1;
		this.end = 5;
		 if(totalPage<=5){
             this.end= this.totalPage;

四、部分程式碼

jsp:

    (1)發出請求

   

   (2)資料顯示

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>學生分頁展示</title>
  </head>
  
  <body>

      共有${page.totalCount }個分類,共有${page.totalPage }頁,當前為第${page.currentPage }頁,每頁顯示${page.pageCount }條
    <table align="center" width="100%">
        <thead>
            <th>選擇</th>
            <th>序號</th>
            <th>使用者名稱</th>
            <th>密碼</th>
            <th>操作</th>
        </thead>
        <tbody align="center" border="1">
            <c:forEach items="${page.pageData }" var="student">
                <tr>
                <td><input  type="checkbox" name="id"/></td>
                <td>${student.id }</td>
                <td>${student.username }</td>
                <td>${student.password }</td>
                <td><a href="${pageContext.request.contextPath }/adminServlet/adminEditStudentServlet?id=${student.id }">修改</a>|<a href="${pageContext.request.contextPath }/adminServlet/adminDeleteStudentServlet?id=${student.id }">刪除</a></td>
                <td></td>
            </tr>
            </c:forEach>
        </tbody>
    </table>
    <!-- 分頁 -->
    <div style="text-align:center;">
        <a href="${pageContext.request.contextPath }/adminServlet/findManyStudentServlet?page=1">首頁</a>
        <!-- 如果當前頁為第一頁,就沒有上一頁這個標籤 -->
        <c:if test="${page.currentPage==1 }">
            <c:forEach begin="${page.start }" end="${page.end }" step="1" var="i">
                <c:if test="${page.currentPage == i}">
                        ${i}
                </c:if>                
                <c:if test="${page.currentPage != i}">
                        <a href="${pageContext.request.contextPath}/adminServlet/findManyStudentServlet?page=${i}">${i}</a>                                        
                 </c:if> 
            </c:forEach>
            <a href="${pageContext.request.contextPath }/adminServlet/findManyStudentServlet?page=${page.currentPage+1}">下一頁</a>
        </c:if>
        <!-- 如果不是首頁也不是尾頁,就與上一頁和下一頁 -->
        <c:if test="${page.currentPage>1 && page.currentPage<page.totalPage }">
            <a href="${pageContext.request.contextPath }/adminServlet/findManyStudentServlet?page=${page.currentPage-1}">上一頁</a>
            <c:forEach begin="${page.start }" end="${page.end }" step="1" var="i">
                <c:if test="${page.currentPage == i}">
                        ${i}
                </c:if>                
                <c:if test="${page.currentPage != i}">
                        <a href="${pageContext.request.contextPath}/adminServlet/findManyStudentServlet?page=${i}">${i}</a>                                        
                 </c:if> 
            </c:forEach>
            <a href="${pageContext.request.contextPath }/adminServlet/findManyStudentServlet?page=${page.currentPage+1}">下一頁</a>
        </c:if>
        <!-- 如果是最後一頁,則沒有下一頁 -->
        <c:if test="${page.currentPage==page.totalPage }">
            <a href="${pageContext.request.contextPath }/adminServlet/findManyStudentServlet?page=${page.currentPage-1}">上一頁</a>
            <c:forEach begin="${page.start }" end="${page.end }" step="1" var="i">
                <c:if test="${page.currentPage == i}">
                        ${i}
                </c:if>                
                <c:if test="${page.currentPage != i}">
                        <a href="${pageContext.request.contextPath}/adminServlet/findManyStudentServlet?page=${i}">${i}</a>                                        
                 </c:if> 
            </c:forEach>
        </c:if>
         <a href="${pageContext.request.contextPath }/adminServlet/findManyStudentServlet?page=${page.totalPage}">尾頁</a>
   </div>
  </body>
</html>

servlet:

   (1)action

public class FindManyStudentServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	    String pageStr = request.getParameter("page");//當前頁數,需要從jsp頁面傳過來
	    System.out.println("請求的頁面" + pageStr);
	    int CurrentPage = Integer.parseInt(pageStr);
	    int pageCount = 6; //每頁顯示的數量
		StudentService service = new StudentService();
		PageBean<Student> page = service.findManyStudent(CurrentPage,pageCount);//分頁查詢
		if(page != null){
		   request.setAttribute("page", page);
		   request.getRequestDispatcher("/admin/jsp/show.jsp").forward(request, response);
		}
	}	
}

 (2)service

//分頁查詢
	public PageBean<Student> findManyStudent(int currentPage, int pageCount) {
		int totalCount = dao.findAllCount();//查詢一共有多少條資料
		PageBean<Student> page = new PageBean<Student>(currentPage,pageCount,totalCount);//建立一個分頁查詢的工具類物件,下面已經提供了分頁查詢的工具類,耐心觀看
		int begin = page.getBegin();
		page.setPageData(dao.findManyStudent(begin,pageCount));
		return page;
	}

  (3)dao  宣告,這裡面我使用了一個工具類和此次分頁無關,所以就不在此展示了

public List<Student> findManyStudent(int begin, int pageCount) {
		String sql = "select * from students limit ?,?";
		List<Student> list = new ArrayList<Student>();
		List<Map<String,Object>> listmap= new ArrayList<Map<String,Object>>();
		Map<String ,Object> map = new HashMap<String ,Object>();
		List<Object> params = new ArrayList<Object>();
		params.add(begin);
		params.add(pageCount);
		dataSourse= new DataUtil();
		try {
			listmap = dataSourse.ManyResult(sql,params);//使用了工具類
			int len = listmap.size();
			for(int i = 0 ; i < len ; i++){
				map = listmap.get(i);
				Student student = new Student();
				student.setId((Integer)map.get("id"));
				student.setUsername((String)map.get("username"));
				student.setPassword((String)map.get("password"));
				list.add(student);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

util:

public class PageBean<T> implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private int currentPage ;//當前頁數,時頁面請求發過來的
	private int pageCount;//每頁多少資料
	private int totalCount;//一共有多少記錄
	private int totalPage;//計算獲得
	private int begin;//limit
	private List<T> pageData;
	
	private int start;
	private int end;
	
	public PageBean(int currentPage,int pageCount,int totalCount){
		//可以直接獲得
		this.currentPage = currentPage;//請求的頁數
		this.pageCount = pageCount;//每頁顯示的數量
		this.totalCount = totalCount;//一共多少條記錄
		//進行計算
		if(totalCount % pageCount == 0){
			this.totalPage = this.totalCount / pageCount;
		}else{
			this.totalPage = this.totalCount / pageCount + 1;
		}
		
		this.begin = (this.currentPage - 1) * pageCount;
		
		//分頁現實的頁數
		this.start = 1;
		this.end = 5;
		 if(totalPage<=5){
             this.end= this.totalPage;
         }else{

             this.start=currentPage-2;
             this.end = currentPage+2;
             
             if(start<=0){
                 this.start=1;
                 this.end=5;
             }
             if(this.end > this.totalPage){
                 this.end=totalPage;
                 this.start=end-4;
             }
         }

	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getBegin() {
		return begin;
	}

	public void setBegin(int begin) {
		this.begin = begin;
	}

	public List<T> getPageData() {
		return pageData;
	}

	public void setPageData(List<T> pageData) {
		this.pageData = pageData;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}
	
}