首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP 分頁顯示完整實作教學

     編輯:關於JSP

核心三層架構實作

1. 資料存取層:MySQL LIMIT 關鍵字

SELECT * FROM tablename LIMIT startPoint, numberPerPage;
-- startPoint: 起始位置-1
-- numberPerPage: 每頁筆數
-- 例:SELECT * FROM comment LIMIT 20,5;  -- 取第 21-25 筆

2. 前端呈現層:jQuery load 非同步載入

function goToPage(page) {
    $('body').load("getComments.do?page=" + page);
}

// 或雙參數版本
function goToPage(page, numberPerPage) {
    $('body').load("getComments.do?page=" + page + "&npp=" + numberPerPage);
}

3. 控制層:Servlet 接收參數組織內容

int page = Integer.parseInt(req.getParameter("page"));

分頁邏輯計算

頁碼列表計算演算法

int total = sm.getCommentCount();
int totalPage = total / itemsPerPage;
if (total % itemsPerPage != 0) totalPage += 1;

Vector<Integer> pageArr = new Vector<Integer>();
int start = 1;
if (page >= 10) start = page / 10 * 10;

int num = start;
while (!(num > totalPage || num > start + 10)) {
    pageArr.add(new Integer(num));
    ++num;
}

處理特殊情況:總頁數不足 10 頁、非 10 倍數。

JSP 頁面顯示分頁控制項

<div id="pageControl">
  <!-- 上一頁 -->
  <c:choose>
    <c:when test="${page != 1}">
      <a href="checkComments.do?page=${page-1}"><input type="button" name="lastPage" value="上一頁" /></a>
    </c:when>
    <c:otherwise>
      <input type="button" disabled="true" name="lastPage" value="上一頁" />
    </c:otherwise>
  </c:choose>

  <!-- 頁碼列表 -->
  <c:forEach items="${pageList}" var="item">
    <c:choose>
      <c:when test="${item == page}">
        <a href="checkComments.do?page=${item}" class="currentPage">${item}</a>
      </c:when>
      <c:otherwise>
        <a href="checkComments.do?page=${item}">${item}</a>
      </c:otherwise>
    </c:choose>
  </c:forEach>

  <!-- 下一頁 -->
  <c:choose>
    <c:when test="${page != totalPages}">
      <a href="checkComments.do?page=${page+1}"><input type="button" name="nextPage" value="下一頁" /></a>
    </c:when>
    <c:otherwise>
      <input type="button" disabled="true" name="nextPage" value="下一頁" />
    </c:otherwise>
  </c:choose>

  <!-- 直接跳轉 -->
  共${totalPages}頁 - 向<input type="text" id="jumpTo" />頁 <input type="button" value="跳轉" onclick="jumpTo(${totalPages})" />
</div>

跳轉 JavaScript 函數

function jumpTo(maxPage) {
    var page = $("#jumpTo").val();
    if (page > maxPage || page < 1) {
        alert("對不起,無法到達該頁");
    } else {
        $('body').load('checkComments.do?page=' + page);
    }
}

CSS 美化效果

.currentPage {
    font-weight: bold;
    color: #ff9a00;
}
#jumpTo { width: 20px; }
#pageControl a { text-decoration: none; }

改進建議

  • 移除連結底線、增加 hover 效果
  • 考慮使用更現代化前端框架(Vue/React)替代 jQuery
  • 後端改用 RESTful API 回傳 JSON,前端渲染分頁元件
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved