萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 分頁顯示完整實作:MySQL LIMIT + jQuery AJAX + Servlet + JSTL

分頁核心三要素

  1. 資料層:MySQL `LIMIT offset, count` 截取指定範圍記錄
  2. 前端:jQuery AJAX 非同步載入分頁片段,無需整頁重載
  3. 後端:Servlet 接收參數、計算分頁資訊、轉發 JSP 片段渲染

1. 資料庫查詢 (DAO 層)

-- MySQL 分頁語法
SELECT * FROM comment 
ORDER BY create_time DESC
LIMIT #{startIndex}, #{pageSize};

-- 參數計算
startIndex = (pageNumber - 1) * pageSize
-- 第 1 頁: LIMIT 0, 10
-- 第 2 頁: LIMIT 10, 10
-- 第 N 頁: LIMIT (N-1)*pageSize, pageSize

2. 前端頁面 (JSP + jQuery)

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<div id="commentList">
    <c:import url="commentListFragment.jsp" />
</div>

<div id="pagination">
    <!-- 頁碼由 Fragment 產生 -->
</div>

<script>
function goToPage(page) {
    $('#commentList').load('commentList.do?page=' + page);
}

function jumpTo(maxPage) {
    var page = $('#jumpTo').val();
    if (page > maxPage || page < 1) {
        alert('頁碼超出範圍');
        return;
    }
    goToPage(page);
}
</script>

<input type="text" id="jumpTo" style="width:40px" placeholder="頁碼" />
<button onclick="jumpTo(${totalPages})">跳轉</button>

3. 片段頁面 (commentListFragment.jsp)

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>

<table class="comment-table">
    <c:forEach items="${commentList}" var="comment">
        <tr>
            <td>${comment.id}</td>
            <td>${comment.content}</td>
            <td>${comment.author}</td>
            <td>${comment.createTime}</td>
        </tr>
    </c:forEach>
</table>

<div id="pageControl">
    <c:choose>
        <c:when test="${page > 1}">
            <a href="javascript:goToPage(${page-1})">上一頁</a>
        </c:when>
        <c:otherwise>
            <span class="disabled">上一頁</span>
        </c:otherwise>
    </c:choose>

    <c:forEach items="${pageList}" var="p">
        <c:choose>
            <c:when test="${p == page}">
                <span class="current-page">${p}</span>
            </c:when>
            <c:otherwise>
                <a href="javascript:goToPage(${p})">${p}</a>
            </c:otherwise>
        </c:choose>
    </c:forEach>

    <c:choose>
        <c:when test="${page < totalPages}">
            <a href="javascript:goToPage(${page+1})">下一頁</a>
        </c:when>
        <c:otherwise>
            <span class="disabled">下一頁</span>
        </c:otherwise>
    </c:choose>
    
    共 ${totalPages} 頁
</div>

4. Servlet 控制器

@WebServlet("/commentList.do")
public class CommentListServlet extends HttpServlet {
    private static final int PAGE_SIZE = 10;
    private static final int PAGE_GROUP = 10; // 頁碼群組大小
    
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        int page = 1;
        try {
            String pageParam = req.getParameter("page");
            if (pageParam != null) page = Integer.parseInt(pageParam);
        } catch (NumberFormatException ignored) {}
        
        // 1. 取得總筆數
        int total = commentService.getCount();
        int totalPages = (int) Math.ceil((double) total / PAGE_SIZE);
        page = Math.max(1, Math.min(page, totalPages));
        
        // 2. 查詢當頁資料
        int start = (page - 1) * PAGE_SIZE;
        List list = commentService.findByPage(start, PAGE_SIZE);
        
        // 3. 計算顯示頁碼範圍 (如 1-10, 11-20...)
        int startPage = ((page - 1) / PAGE_GROUP) * PAGE_GROUP + 1;
        int endPage = Math.min(startPage + PAGE_GROUP - 1, totalPages);
        List pageList = new ArrayList<>();
        for (int i = startPage; i <= endPage; i++) pageList.add(i);
        
        // 4. 設定屬性轉發片段頁面
        req.setAttribute("commentList", list);
        req.setAttribute("page", page);
        req.setAttribute("totalPages", totalPages);
        req.setAttribute("pageList", pageList);
        
        req.getRequestDispatcher("/WEB-INF/jsp/commentListFragment.jsp")
           .forward(req, resp);
    }
}

5. CSS 美化

#pageControl a { text-decoration: none; padding: 4px 8px; margin: 0 2px; border: 1px solid #ddd; }
#pageControl a:hover { background: #eee; }
#pageControl .current-page { font-weight: bold; color: #ff9a00; padding: 4px 8px; }
#pageControl .disabled { color: #999; padding: 4px 8px; }
#jumpTo { width: 40px; text-align: center; }

關鍵設計要點

  • 片段化:`` / AJAX 載入片段,避免整頁重繪
  • 頁碼群組:大量頁面時只顯示鄰近頁碼 (如 10 個一組)
  • 參數驗證:頁碼邊界檢查、預防 SQL 注入 (使用 PreparedStatement)
  • 效能優化:大資料量建議游標分頁或延遲關聯,避免 `OFFSET` 深分頁效能下降
copyright © 萬盛學電腦網 all rights reserved