第一次使用 Bootstrap Table 是為了做列表的後端分頁。翻過官方範例檔(bootstrap-table examples)之後,才搞清楚兩個關鍵參數:每頁筆數 limit 與起始筆數 offset。以下把整個串接過程整理出來,包含前端表格設定與後端(Spring + Hibernate)的處理。
$('#table').bootstrapTable({
url: '<%=path%>/FeedList.cqzk',
striped: true,
pagination: true,
pageList: [3, 5, 20],
pageSize: 3,
pageNumber: 1,
sidePagination: 'server', // 改用伺服器端分頁
columns: [
{ field: 'title', title: '標題' },
{ field: 'creatTime', title: '時間' }
]
});
sidePagination 設為 'server' 之後,表格就會把分頁資訊當成查詢參數送到後端,而不是在前端切割資料。
@RequestMapping(value = "/FeedList.cqzk")
@ResponseBody
public String url_ad1(HttpServletRequest request, BootPage page)
throws ServletException, IOException, RuntimeException {
BootPage pager = feedBackDao.getByPage("from Feedback", page, null);
// 加上 getString(0) 才會回傳單一物件;不加會多包一層中括號變成陣列
return JSONArray.fromObject(pager).getString(0).toString();
}
DAO 層負責依分頁參數取資料,並另行計算總筆數:
public BootPage getByPage(String hql, BootPage pager, Map<String, Object> condition) {
if (pager == null) {
throw new IllegalArgumentException("分頁參數不能為空!");
}
Query q = sessionFactory.getCurrentSession().createQuery(hql);
q.setFirstResult(pager.getOffset()); // 起始筆數
q.setMaxResults(pager.getLimit()); // 每頁筆數
if (condition != null) {
q.setProperties(condition);
}
pager.setRows(q.list());
pager.setTotal(this.countAll(hql, condition));
return pager;
}
protected Long countAll(String hql, Map<String, Object> condition) {
if (hql == null) {
return 0L;
}
String tmpHql = hql.toLowerCase();
String regex = hql.substring(0, tmpHql.indexOf("from"));
hql = hql.replaceFirst(regex, "select count(*) ");
Query q = sessionFactory.getCurrentSession().createQuery(hql);
if (condition != null) {
q.setProperties(condition);
}
return (Long) q.uniqueResult();
}
最後自訂一個承載分頁資訊的類別,欄位名稱剛好對應 Bootstrap Table 期望的格式:
public final class BootPage<T> {
protected Long total; // 總筆數
protected List<T> rows; // 目前頁的資料
protected int limit = 0; // 每頁筆數
protected int offset = 0; // 起始位移
protected String order = "asc";
// getter / setter 略
}
整條流程就是:Bootstrap Table 送出 limit 與 offset,後端用 setFirstResult 與 setMaxResults 對應,再把 rows 與 total 打包成 JSON 回傳。釐清這兩個參數的意義之後,換成 MySQL、SQL Server 或任何 ORM 都只是語法差異而已。