这里这个类为PageBean.java,里面是定义我们要用到的几个参数,然后提供参数的get和set方法,其实和我们之前写的实体类很像…
package cn.itcast.shop.utils;
import java.util.List;
/**
* 分页类的封装
* @author wxr
* @param <T>
*
*/
public class PageBean<T> {
private int page; //当前页数
private int totalCount; //总记录数
private int totalPage; //总页数
private int limit; //每页显示的记录数
private List<T> list; //每页显示数据的集合
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
JSP需要从后台获取值显示:
<tr align="center">
<td colspan="4">
第<s:property value="pageBean.page"/>/<s:property value="pageBean.totalPage"/>页
<s:if test="pageBean.page!=1">
<a href="${pageContext.request.contextPath }/adminProduct_findAll.action?page=1">首页</a>|
<a href="${pageContext.request.contextPath }/adminProduct_findAll.action?page=<s:property value="pageBean.page-1"/>">上一页</a>|
</s:if>
<s:if test="pageBean.page!=pageBean.totalPage">
<a href="${pageContext.request.contextPath }/adminProduct_findAll.action?page=<s:property value="pageBean.page+1"/>">下一页</a>|
<a href="${pageContext.request.contextPath }/adminProduct_findAll.action?page=<s:property value="pageBean.totalPage"/>">尾页</a>
</s:if>
</td>
</tr>
需要在adminProduct.Action中进行查询FindAll
//带分页的查询商品的执行方法
public String findAll(){
//调用Service完成查询操作
PageBean<Product> pageBean =productService.findByPage(page);
//将数据传递到页面上
ActionContext.getContext().getValueStack().set("pageBean", pageBean);
//页面跳转
return "findAll";
}
Action调用业务逻辑层Service
/业务层查询商品带分页的方法
public PageBean<Product> findByPage(Integer page) {
PageBean<Product> pageBean=new PageBean<Product>();
//设置当前页数;
pageBean.setPage(page);
//设置每页显示记录数
int limit=10;
pageBean.setLimit(limit);
//设置总记录条数
int totalCount=productDao.findCount();
pageBean.setTotalCount(totalCount);
//设置总页数
int totalPage=0;
if(totalCount % limit==0){
totalPage=totalCount/limit;
}else{
totalPage=totalCount/limit+1;
}
pageBean.setTotalPage(totalPage);
//设置显示到页面的数据的集合
int begin=(page-1)*limit;
List<Product> list=productDao.findByPage(begin,limit);
pageBean.setList(list);
return pageBean;
}
在这方面中设置分页查询需要的两个参数begin(从那条开始查)limit(查询几条也就是每页显示几条)
然后调用Dao层从数据库中进行查询
//带分页查询商品的方法
public List<Product> findByPage(int begin, int limit) {
String hql="from Product order by pdate desc";
List<Product> list=this.getHibernateTemplate().execute(new PageHibernateCallback<Product>(hql,null,begin,limit));
if(list!=null && list.size()>0){
return list;
}
return null;
}