currentPage = httpServletRequest.getParameter("currentPage");
//如果当前页号为空,表示为首次查询该页
//如果不为空,则刷新pager对象,输入当前页号等信息
if (currentPage != null) {
pager.refresh(Integer.parseInt(currentPage));
}
//获取当前执行的方法,首页,前一页,后一页,尾页。
String pagerMethod = httpServletRequest.getParameter("pageMethod");
if (pagerMethod != null) {
if (pagerMethod.equals("first")) {
pager.first();
} else if (pagerMethod.equals("previous")) {
pager.previous();
} else if (pagerMethod.equals("next")) {
pager.next();
} else if (pagerMethod.equals("last")) {
pager.last();
}
}
return pager;
}
}
PageHelper这个类,我不用说应该也知道用来干嘛了
3.DAO类
package com.jpcf.db.dao;
import com.jpcf.db.model.*;
import com.jpcf.db.helper.HibernateUtil;
import net.sf.hibernate.*;
import java.util.*;
import com.jpcf.db.controller.*;
public class VehiclePropertyDAO {
public Collection findWithPage(int pageSize, int startRow) throws
HibernateException {
Collection vehicleList = null;
Transaction tx = null;
try {
Session session = HibernateUtil.currentSession();
tx = session.beginTransaction();
Query q = session.createQuery("from VehicleProperty vp");
q.setFirstResult(startRow);
q.setMaxResults(pageSize);
vehicleList = q.list();
tx.commit();
} catch (HibernateException he) {
if (tx != null) {
tx.rollback();
}
throw he;
} finally {
HibernateUtil.closeSession();
}
return vehicleList;
}
public int getRows(String query) throws
HibernateException {
int totalRows = 0;
Transaction tx = null;
try {
Session session = HibernateUtil.currentSession();
tx = session.beginTransaction();
totalRows = ((Integer) session.iterate(query).next()).
intValue();
tx.commit();
} catch (HibernateException he) {
if (tx != null) {
tx.rollback();
}
throw he;
} finally {
HibernateUtil.closeSession();
}
return totalRows;
}
}
DAO类我就贴这些分页需要的代码了。
“from VehicleProperty vp”也可以用一个参数传进来,有兴趣的自己改一下吧
Hibernate实现Struts分页中的分页处理(3)
时间:2011-03-23
4.Action
下面是在Action中用到的代码:
public ActionForward queryWithPage(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletresponse) {
Collection clInfos = null;//用于输出到页面的记录集合
int totalRows;//记录总行数
VehiclePropertyDAO vehicleDAO = new VehiclePropertyDAO();
//取得当前表中的总行数
try {
totalRows = vehicleDAO.getRows("select count(*) from VehicleProperty");
} catch (Exception ex) {
servlet.log(ex.toString());
return actionMapping.findForward(Constants.FAILURE);
}
//通过PagerHelper类来获取用于输出到页面的pager对象
Pager pager=PagerHelper.getPager(httpServletRequest,totalRows);
//取出从startRow开始的pageSize行记录
try {
clInfos = vehicleDAO.findWithPage(pager.getPageSize(), p
|