1、我们一般使用pager-taglib、displaytag、spring中PagedListHolder组件来对大量的结果集进行分页
2、在使用这些组件之前,一定引入相应的jar包
3、对分页的总结(pager-taglib):
①在页面中加入下面的代码:
<pg:pager url="module.action" items="${pm.total }" export="currentPageNumber=pageNumber" maxPageItems="5" isOffset="true">
<pg:param name="parentId"/>
<pg:first>
<a href="${pageUrl}">首页</a>
</pg:first>
<pg:prev>
<a href="${pageUrl }">前页</a>
</pg:prev>
<pg:pages>
<c:choose>
<c:when test="${currentPageNumber eq pageNumber }">
<font color="red">${pageNumber }</font>
</c:when>
<c:otherwise>
<a href="${pageUrl }">${pageNumber }</a>
</c:otherwise>
</c:choose>
</pg:pages>
<pg:next>
<a href="${pageUrl }">后页</a>
</pg:next>
<pg:last>
<a href="${pageUrl }">尾页</a>
</pg:last>
</pg:pager>
②前台页面中需要获得:(要进行分页的总记录数、当前页面的结果集)
PageModel.java
public class PagerModel {
/**
* 总记录数
*/
private int total;
//当前页的结果集
private List<Organization> list;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
/**
* 返回Organization的集合
* @return List<Organization> (size >=0)
*/
public List<Organization> getList() {
return list == null? Collections.<Organization>emptyList() : list;
}
public void setList(List<Organization> list) {
this.list = list;
}
}
④ 在需要进行分页的模块中,创建相应的方法比如:
/**
* 分页查询模块的信息
* @param parentId
* @return
*/
public PagerModel searchModules(int parentId,int offset,int pagesize);
⑤ 在对应的业务逻辑中去实现它
public PagerModel searchModules(int parentId,int offset,int pagesize) {
return this.searchPaginated("select m from Module m where " + (parentId ==0 ? "m.parent is null" : ("m.parent.id = " + parentId)), null, offset, pagesize);
}
⑥searchPaginated方法的实现如下:
public PagerModel searchPaginated(String hql,Object[] params, int offset, int pagesize) {
//获取总记录数
String countHql = this.getCountQuery(hql);
System.out.println("countHql: " + countHql);
Query query = this.getSession().createQuery(countHql);
if(query != null && params != null && params.length > 0) {
for(int i=0; i<params.length; i++) {
query.setParameter(i, params[i]);
}
}
int total = ((Long)query.uniqueResult()).intValue();
//获得当前页的结果集
query = this.getSession().createQuery(hql);
if(query != null && params != null && params.length > 0) {
for(int i=0; i<params.length; i++) {
query.setParameter(i, params[i]);
}
}
query.setFirstResult(offset);
query.setMaxResults(pagesize);
List<Organization> list = query.list();
PagerModel pm = new PagerModel();
pm.setTotal(total);
pm.setList(list);
return pm;
}