---
title: " Struts+Hibernate开发实践 分页的实现"
author: "aijun980204"
date: "2010-04-24T10:44:28Z"
tags: ["Bean", "DAO", "Hibernate", "JSP", "Struts"]
categories: ["编程语言"]
slug: "struts-hibernate"
draft: false
lastmod: "2010-04-24T10:44:28Z"
id: 651969
url: "https://aijun980204.iteye.com/blog/651969"
---

在进行web应用开发的时候经常要进行分页处理，经常看到一些人在问分页处理的问题，现在我把自己的处理方法写在这儿，希望能对需要进行分页处理的朋友有所帮助。

一、在struts中分页有两种结构：  
1\. 在Action中通过DAO查询出所有的记录，然后加到session或request对象中，传到客户端，由JSP进行分页。  
这种方法对于在数据量少的时候很方便，也不影响速度。  
2.在Action中每次通过DAO只查询出一页的记录，再传给JSP页面。  
这种结构对于数据量大的程序很好，但对于数据量小的情况，会增加对服务器的请求，加大服务器的负载。  
二、Hibernate查询  
由于在Hibernate中直接提供了对数据库定点定量的查询方法，所以我采用的是第2种方法。

如：  
从第1万条开始取出100条记录  
Query q = session.createQuery("from Cat as c");

q.setFirstResult(10000);  
q.setMaxResults(100);  
List l = q.list();

三、具体实现

1.Pager类

package com.jpcf.db.helper;  
import java.math.\*;  
public class Pager {  
private int totalRows; //总行数  
private int pageSize = 10; //每页显示的行数  
private int currentPage; //当前页号  
private int totalPages; //总页数  
private int startRow; //当前页在数据库中的起始行  
public Pager() {  
}  
public Pager(int \_totalRows) {  
totalRows = \_totalRows;  
totalPages=totalRows/pageSize;  
int mod=totalRows%pageSize;  
if(mod&gt;0){  
totalPages++;  
}  
currentPage = 1;  
startRow = 0;  
}  
public int getStartRow() {  
return startRow;  
}  
public int getTotalPages() {  
return totalPages;  
}  
public int getCurrentPage() {  
return currentPage;  
}  
public int getPageSize() {  
return pageSize;  
}  
public void setTotalRows(int totalRows) {  
this.totalRows = totalRows;  
}  
public void setStartRow(int startRow) {  
this.startRow = startRow;  
}  
public void setTotalPages(int totalPages) {  
this.totalPages = totalPages;  
}  
public void setCurrentPage(int currentPage) {  
this.currentPage = currentPage;  
}  
public void setPageSize(int pageSize) {  
this.pageSize = pageSize;  
}  
public int getTotalRows() {  
return totalRows;  
}  
public void first() {  
currentPage = 1;  
startRow = 0;  
}  
public void previous() {  
if (currentPage == 1) {  
return;  
}  
currentPage--;  
startRow = (currentPage - 1) * pageSize;  
}  
public void next() {  
if (currentPage &lt; totalPages) {  
currentPage++;  
}  
startRow = (currentPage - 1) * pageSize;  
}  
public void last() {  
currentPage = totalPages;  
startRow = (currentPage - 1) * pageSize;  
}  
public void refresh(int \_currentPage) {  
currentPage = \_currentPage;  
if (currentPage &gt; totalPages) {  
last();  
}  
}  
}

Pager类用于计算首页、前一页、下一页、尾页的在数据库中的起始行，当前的页码。

2.PagerHelp类

package com.jpcf.db.helper;  
import javax.servlet.http.\*;  
public class PagerHelper {  
public static Pager getPager(HttpServletRequest httpServletRequest,  
int totalRows) {  
//定义pager对象，用于传到页面  
Pager pager = new Pager(totalRows);  
//从Request对象中获取当前页号  
String 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”也可以用一个参数传进来，有兴趣的自己改一下吧

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(), pager.getStartRow());  
} catch (Exception ex) {  
servlet.log(ex.toString());  
return actionMapping.findForward(Constants.FAILURE);  
}  
//把输出的记录集和pager对象保存到request对象中  
httpServletRequest.setAttribute("CLINFOS", clInfos);  
httpServletRequest.setAttribute("PAGER", pager);  
return actionMapping.findForward(Constants.SUCCESS);  
}

查询语句select count(\*) from VehicleProperty 也可以换成你需要的任意的条件（select count(\*) from VehicleProperty where ..)

5.JSP页面使用

下面就是在JSP中的应用了：

&lt;td colspan="8" align="right" class="head"&gt;  
第&lt;bean:write name="PAGER" property="currentPage"/&gt;页&nbsp;  
共&lt;bean:write name="PAGER" property="totalPages"/&gt;页&nbsp;  
&lt;html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&amp;pageMethod=first" paramName="PAGER" paramProperty="currentPage" paramId="currentPage"&gt;首页&lt;/html:link&gt;  
&lt;html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&amp;pageMethod=previous" paramName="PAGER" paramProperty="currentPage" paramId="currentPage"&gt;上一页&lt;/html:link&gt;  
&lt;html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&amp;pageMethod=next" paramName="PAGER" paramProperty="currentPage" paramId="currentPage"&gt;下一页&lt;/html:link&gt;  
&lt;html:link action="/bussiness/clInfo/queryWithPage.do?method=queryWithPage&amp;pageMethod=last" paramName="PAGER" paramProperty="currentPage" paramId="currentPage"&gt;尾页&lt;/html:link&gt;  
&lt;/td&gt;

解释一下这一行:"/bussiness/clInfo/queryWithPage.do?method=queryWithPage&amp;pageMethod=first  
method=queryWithPage 是由于我的Action继承的是DispatchAction,需要一个method参数  
pageMethod=first 是用来在PageHelper类中判断执行哪个操作

四、总结

我做的这个也只是一个借鉴，还有很多没有实现的，比如还可以加一下 go 直接到第n页的功能。

其实最关键的是把当前页号和要执行的是功能(上一页，下一页)的参数从页面传进来，在Action中就可以根据这两个参数去取下一个页面上要显示的记录集了