分頁是業務系統高頻需求。一個設計良好的分頁工具類,能屏蔽頁碼計算邏輯,統一前後端交互契約。本文提供生產級 Pager<T> 實現與測試示例。
| 屬性 | 含義 | 默認值 |
|---|---|---|
| currentPage | 當前頁碼 | 1 |
| pageSize | 每頁條數 | 10 |
| recordTotal | 總記錄數 | 0 |
| pageTotal | 總頁數(自動計算) | - |
| firstPage | 首頁頁碼 | 1 |
| lastPage | 尾頁頁碼 | - |
| previousPage | 上一頁頁碼 | - |
| nextPage | 下一頁頁碼 | - |
| content | 當前頁數據列表 | null |
public void otherAttr() {
// 總頁數 = (總記錄數 + 每頁大小 - 1) / 每頁大小
this.pageTotal = this.recordTotal % this.pageSize > 0
? this.recordTotal / this.pageSize + 1
: this.recordTotal / this.pageSize;
this.firstPage = 1;
this.lastPage = this.pageTotal;
// 上一頁:首頁時停留在首頁
this.previousPage = this.currentPage > 1 ? this.currentPage - 1 : this.firstPage;
// 下一頁:尾頁時停留在尾頁
this.nextPage = this.currentPage < this.lastPage ? this.currentPage + 1 : this.lastPage;
}
調用時機:setRecordTotal() 內部自動調用,確保總記錄數變更時衍生屬性同步更新。
public class Pager<T> implements Serializable {
private static final long serialVersionUID = 4542617637761955078L;
private int currentPage = 1;
private int pageSize = 10;
private int pageTotal;
private int recordTotal = 0;
private int previousPage;
private int nextPage;
private int firstPage = 1;
private int lastPage;
private List<T> content;
// Setter 方法...
public void setRecordTotal(int recordTotal) {
this.recordTotal = recordTotal;
otherAttr(); // 關鍵:同步計算衍生屬性
}
public void setContent(List<T> content) { this.content = content; }
// Getter 方法...
public int getCurrentPage() { return currentPage; }
// ... 其他 getter
@Override public String toString() {
return "Pager[currentPage=" + currentPage + ", pageSize=" + pageSize
+ ", pageTotal=" + pageTotal + ", recordTotal=" + recordTotal
+ ", content=" + content + "]";
}
}
public class PagerTester {
public static void main(String[] args) {
Pager<String> pager = new Pager<>();
// 模擬數據源
List<String> data = new ArrayList<>();
for (int i = 1; i <= 10; i++) data.add("str" + i);
// 設置分頁參數:第1頁,每頁10條,總共62條
pager.setCurrentPage(1);
pager.setPageSize(10);
pager.setRecordTotal(62); // 觸發 otherAttr() 計算 pageTotal=7 等
pager.setContent(data); // 僅設置當前頁數據
System.out.println(pager);
// 輸出: Pager[currentPage=1, pageSize=10, pageTotal=7, recordTotal=62, ...]
}
}
firstPage, previousPage, nextPage, lastPage, pageTotal 渲染分頁條PageHelper 或自定義攔截器自動注入 LIMIT/OFFSETsetCurrentPage 修正非法值(<1 設為 1,>pageTotal 設為 pageTotal)Serializable 便於分布式傳輸Pager<T> 以泛型適配任意數據類型,封裝分頁元數據計算邏輯,提供豐富導航屬性,是 Service 層返回列表數據的標準載體。實際項目中建議結合分頁插件使用,Service 僅負責組裝 Pager 對象返回 Controller。