設計目標
- 零侵入:不綁定具體業務邏輯,只負責分頁邏輯與 HTML 渲染
- 靈活配置:頁碼組數、每頁條數、URL 模板、樣式類名均可配置
- 性能優化:大數據量時避免全表掃描,支持延遲加載/游標分頁
- 易用性:JSP 標籤或工具類雙模式調用
核心數據模型
public class PageContext {
private int pageNo = 1; // 當前頁 (1-based)
private int pageSize = 20; // 每頁條數
private long totalRows = 0; // 總記錄數
private int pageGroupSize = 10; // 頁碼組大小 (如 1-10, 11-20)
private String urlTemplate; // 分頁鏈接模板: "/list?page={page}"
private Map params; // 額外查詢參數保持
// 計算屬性
public int getTotalPages() { return (int) Math.ceil((double) totalRows / pageSize); }
public int getStartPage() { /* 計算當前組起始頁 */ }
public int getEndPage() { /* 計算當前組結束頁 */ }
public boolean hasPrev() { return pageNo > 1; }
public boolean hasNext() { return pageNo < getTotalPages(); }
public String getPageUrl(int page) { /* 替換模板生成 URL */ }
}
工具類實現 (核心邏輯)
public class PaginationUtils {
/**
* 計算分頁上下文,供 JSP/標籤使用
*/
public static PageContext build(HttpServletRequest request,
long totalRows,
String urlTemplate,
int defaultPageSize) {
PageContext pc = new PageContext();
pc.setTotalRows(totalRows);
pc.setUrlTemplate(urlTemplate);
// 1. 解析頁碼參數
String pageParam = request.getParameter("page");
try { pc.setPageNo(pageParam != null ? Integer.parseInt(pageParam) : 1); }
catch (NumberFormatException e) { pc.setPageNo(1); }
pc.setPageNo(Math.max(1, pc.getPageNo()));
// 2. 解析頁面大小 (可選)
String sizeParam = request.getParameter("pageSize");
if (sizeParam != null) {
try { pc.setPageSize(Math.min(100, Math.max(1, Integer.parseInt(sizeParam)))); }
catch (NumberFormatException ignored) {}
} else {
pc.setPageSize(defaultPageSize);
}
// 3. 保持其他查詢參數
Map extraParams = new LinkedHashMap<>();
request.getParameterMap().forEach((k, v) -> {
if (!"page".equals(k) && !"pageSize".equals(k)) {
extraParams.put(k, v.length == 1 ? v[0] : v);
}
});
pc.setParams(extraParams);
// 4. 修正頁碼不超過總頁數
if (pc.getPageNo() > pc.getTotalPages()) {
pc.setPageNo(pc.getTotalPages());
}
return pc;
}
/**
* MySQL 分頁查詢優化 (避免大偏移量性能下降)
*/
public static String buildMysqlPageSql(String baseSql, PageContext pc) {
// 基礎 LIMIT 語法
long offset = (long)(pc.getPageNo() - 1) * pc.getPageSize();
return baseSql + " LIMIT " + offset + ", " + pc.getPageSize();
}
/**
* 游標分頁 (適合超大表、無需跳頁場景)
* 要求:有唯一遞增索引 (如 id, create_time)
*/
public static String buildCursorSql(String baseSql, String cursorColumn,
Object lastValue, int pageSize) {
return baseSql + " WHERE " + cursorColumn + " > ? ORDER BY " + cursorColumn + " LIMIT " + pageSize;
}
}
JSP 標籤實現 <util:pagination>
標籤類
public class PaginationTag extends TagSupport {
private PageContext pageContext; // 注入構建好的分頁上下文
private String styleClass = "pagination"; // ul class
private int maxVisiblePages = 10; // 可見頁碼數
@Override
public int doStartTag() throws JspException {
if (pageContext == null || pageContext.getTotalPages() <= 1) {
return SKIP_BODY; // 無需分頁
}
try {
JspWriter out = pageContext.getOut();
renderPagination(out);
} catch (IOException e) {
throw new JspException(e);
}
return SKIP_BODY;
}
private void renderPagination(JspWriter out) throws IOException {
int current = pageContext.getPageNo();
int total = pageContext.getTotalPages();
int half = maxVisiblePages / 2;
int start = Math.max(1, current - half);
int end = Math.min(total, start + maxVisiblePages - 1);
if (end - start + 1 < maxVisiblePages) {
start = Math.max(1, end - maxVisiblePages + 1);
}
out.println("<nav aria-label='Page navigation'>");
out.println(" <ul class='" + styleClass + "'>");
// 首頁/上一頁
renderPageItem(out, 1, "首頁", current == 1);
renderPageItem(out, current - 1, "上一頁", current == 1);
// 頁碼組
if (start > 1) {
renderPageItem(out, 1, "1", false);
if (start > 2) out.println(" <li class='disabled'><span>...</span></li>");
}
for (int i = start; i <= end; i++) {
renderPageItem(out, i, String.valueOf(i), i == current);
}
if (end < total) {
if (end < total - 1) out.println(" <li class='disabled'><span>...</span></li>");
renderPageItem(out, total, String.valueOf(total), false);
}
// 下一頁/尾頁
renderPageItem(out, current + 1, "下一頁", current == total);
renderPageItem(out, total, "尾頁", current == total);
out.println(" </ul>");
out.println("</nav>");
}
private void renderPageItem(JspWriter out, int page, String label, boolean disabled) throws IOException {
String url = pageContext.getPageUrl(page);
out.print(" <li class='" + (disabled ? "disabled" : "") + (page == pageContext.getPageNo() ? " active" : "") + "'>");
if (disabled) {
out.print("<span>" + label + "</span>");
} else {
out.print("<a href='" + url + "'>" + label + "</a>");
}
out.println("</li>");
}
// Getter/Setter...
}
TLD 定義
<tag>
<name>pagination</name>
<tag-class>com.example.tag.PaginationTag</tag-class>
<body-content>empty</body-content>
<attribute><name>pageContext</name><required>true</required><rtexprvalue>true</rtexprvalue><type>com.example.util.PageContext</type></attribute>
<attribute><name>styleClass</name><rtexprvalue>true</rtexprvalue></attribute>
<attribute><name>maxVisiblePages</name><rtexprvalue>true</rtexprvalue></attribute>
</tag>
JSP 頁面調用示例
<%@ page import="com.example.util.*,com.example.dao.*" %>
<%@ taglib prefix="util" uri="/WEB-INF/tlds/util.tld" %>
<%
// 1. 獲取總記錄數 (可優化為緩存/估算)
long total = new ArticleDao().countByCondition(request.getParameterMap());
// 2. 構建分頁上下文
String urlTpl = request.getRequestURL() + "?page={page}";
PageContext pc = PaginationUtils.build(request, total, urlTpl, 20);
// 3. 查詢當前頁數據
List list = new ArticleDao().findByPage(pc.getPageNo(), pc.getPageSize(), request.getParameterMap());
request.setAttribute("articleList", list);
request.setAttribute("pageContext", pc); // 供標籤使用
%>
<html><body>
<table>
<c:forEach items="${articleList}" var="a">
<tr><td>${a.title}</td><td>${a.createTime}</td></tr>
</c:forEach>
</table>
<!-- 一行代碼渲染完整分頁條 -->
<util:pagination pageContext="${pageContext}" styleClass="pagination pagination-sm" maxVisiblePages="10"/>
</body></html>
大數據量優化策略
| 策略 | 適用場景 | 實現要點 |
| 緩存總數 | 數據變化不頻繁、允許近似值 | Redis 緩存 count 5-10 分鐘;或 SHOW TABLE STATUS 估算 |
| 延遲加載總數 | 首屏不需總頁數、無限滾動 | 只查 pageSize+1 條,有更多則顯示「加載更多」 |
| 游標分頁 | 千萬級表、按時間倒序、無需跳頁 | WHERE id > lastId ORDER BY id LIMIT 20,索引命中快 |
| 覆蓋索引 | 查詢列固定、需極致性能 | 索引包含所有 SELECT 列,避免回表 |
| 分表/分庫 | 單表超 5000萬 | ShardingSphere、Vitess、手動路由 |
前端增強 (可選)
<!-- AJAX 無刷新分頁 -->
<script>
document.querySelector('.pagination').addEventListener('click', function(e) {
var a = e.target.closest('a');
if (!a || a.parentElement.classList.contains('disabled') || a.parentElement.classList.contains('active')) return;
e.preventDefault();
loadPage(a.href); // Fetch + 替換列表區域 + History.pushState
});
</script>
copyright ©
萬盛學電腦網 all rights reserved