struts+hibernate 分页的实现

来源:互联网 发布:兼容性测试软件 编辑:程序博客网 时间:2024/05/24 06:49
在进行web应用开发的时候经常要进行分页处理,经常看到一些人在问分页处理的问题,现在我把自己的处理方法写在这儿,希望能对需要进行分页处理的朋友有所帮助。

一、在struts中分页有两种结构:
 
   1. 在Action中通过DAO查询出所有的记录,然后加到session或request对象中,传到客户端,由JSP进行分页。这种方法对于在数据量少的时候很方便,也不影响速度。

    2.在Action中每次通过DAO只查询出一页的记录,再传给JSP页面。这种结构对于数据量大的程序很好,但对于数据量小的情况,会增加对服务器的请求,加大服务器的负载。

二、Hibernate查询
    由于在Hibernate中直接提供了对数据库定点定量的查询方法,所以我采用的是第2种方法。

如:
从第1万条开始取出100条记录
Query session.createQuery("from Cat as c");
q.setFirstResult(10000);
q.setMaxResults(100);
List q.list();

三、具体实现

 1.Pager类

package com.jpcf.db.helper;

import java.math.*;

public class Pager {
  private int totalRows; //总行数
  private String[] pageNumber;//存放页数列表
  private int pageSize = 10;//每页显示的行数
  private int currentPage; //当前页号
  private int totalPages; //总页数
  private int startRow;//当前页在数据库中的起始行
  boolean hasNext; //是否有下一页
  boolean hasPrevious; //是否有前一页


  public Pager() {
  }

  public Pager(int _totalRows) {
    totalRows =_totalRows;
   totalPages=totalRows/pageSize;
    intmod=totalRows%pageSize;
   if(mod>0){
     totalPages++;
    }
   //设置页数数组
   pageNumber=new String[totalPages];
    int i;
   for(i=0;i<totalPages;i++)
   {
    pageNumber[i]=Integer.toString(i+1);
   }
   
    currentPage= 1;
    startRow =0;
   hasPrevious=false;
   if(totalPages==1)
    {
    hasNext=false;
    }
    else
    {
    hasNext=true;
    }
  }

  public int getStartRow() {
    returnstartRow;
  }

  public int getTotalPages() {
    returntotalPages;
  }

  public int getCurrentPage() {
    returncurrentPage;
  }

  public int getPageSize() {
    returnpageSize;
  }

  public int getTotalRows() {
    returntotalRows;
  }
 
  public String[] getPageNumber() {
   return pageNumber;
  }
 
  public void setPageNumber(String[] pageNumber){
   this.pageNumber =pageNumber;
  }

  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 boolean isHasNext() {
   return hasNext;
   }

  public boolean isHasPrevious() {
   return hasPrevious;
   }


  public void first() {
    currentPage= 1;
    startRow =0;
   hasPrevious=false;
   if(totalPages<=1)
    {
    hasNext=false;
    }
    else
    {
    hasNext=true;
    }
  }

  public void previous() {
    if(currentPage == 1) {
     return;
    }
   currentPage--;
    startRow =(currentPage - 1) * pageSize;
   if(currentPage==1)
    {
     hasPrevious=false;
    }
    else
    {
    hasPrevious=true;
    }
   hasNext=true;
  }

  public void next() {
    if(currentPage < totalPages) {
     currentPage++;
    }
    startRow =(currentPage - 1) * pageSize;
   hasPrevious=true;
   if(currentPage==totalPages)
    {
    hasNext=false;
    }
    else
    {
    hasNext=true;
    }
  }

  public void last() {
    if(totalPages>=1)
    currentPage =totalPages;
    else
   currentPage=1;
   

    startRow= (currentPage - 1) * pageSize;
   hasNext=false;
   if(currentPage==1)
    {
     hasPrevious=false;
    }
    else
    {
    hasPrevious=true;
    }
  }
 
  public void setGotoPage(int i) {
   currentPage = i;
   //计算当前页开始行
  startRow=(currentPage-1)*pageSize;
   if(currentPage==1)
    {
     hasPrevious=false;
     hasNext=true;
    }
   elseif(currentPage==totalPages)
    {
     hasNext=false;
     hasPrevious=true;
    }
   else{
   hasNext=true;
   hasPrevious=true;
   }
  }

  public void refresh(int _currentPage) {
    currentPage= _currentPage;
    if(currentPage > totalPages) {
     last();
    }
  }

}


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

2.PagerHelp类

package com.jpcf.db.helper;

import javax.servlet.http.*;

public class PagerHelper {

  public static PagergetPager(HttpServletRequest httpServletRequest,int totalRows){

   //定义pager对象,用于传到页面
    Pager pager= new Pager(totalRows);

   //从Request对象中获取当前页号
    StringcurrentPage =httpServletRequest.getParameter("currentPage");

   //如果当前页号为空,表示为首次查询该页
   //如果不为空,则刷新pager对象,输入当前页号等信息
    if(currentPage != null) {
     pager.refresh(Integer.parseInt(currentPage));
    }

   //获取当前执行的方法,首页,前一页,后一页,尾页。
    StringpagerMethod =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();
     } else {
      int gotoPage=Integer.parseInt(pagerMethod);
      pager.setGotoPage(gotoPage);
     }
    }
    returnpager;
  }
}


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 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 execute(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中的应用了:

<logic:present name="PAGER">
   第<bean:write name="PAGER"property="currentPage"/>页&nbsp;&nbsp;共<bean:writename="PAGER" property="totalPages"/>页 
   <html:linkaction="/user/examineAction.do?pageMethod=first" 
paramName="PAGER" paramProperty="currentPage" paramId="currentPage">&nbsp;&nbsp;首页</html:link> 

   <logic:equal value="true"name="PAGER" property="hasPrevious">
   <html:linkaction="/user/examineAction.do?pageMethod=previous" 
paramName="PAGER" paramProperty="currentPage" paramId="currentPage">&nbsp;&nbsp;上一页</html:link>
  </logic:equal>

   <logic:iterateid="rownumber" name="PAGER" property="pageNumber">
   <ahref='/worklog/user/examineAction.do?pageMethod=<bean:writename="rownumber" />&currentPage=<bean:write name="PAGER"property="currentPage"/>'><bean:write name="rownumber"/>&nbsp;&nbsp;</a>
   </logic:iterate>

   <logic:equal value="true"name="PAGER" property="hasNext">
   <html:linkaction="/user/examineAction.do?pageMethod=next" 
paramName="PAGER" paramProperty="currentPage" paramId="currentPage">&nbsp;&nbsp;下一页</html:link>
   </logic:equal>

   <html:linkaction="/user/examineAction.do?pageMethod=last" 
paramName="PAGER" paramProperty="currentPage"paramId="currentPage">&nbsp;&nbsp;尾页</html:link>
</logic:present>
  
pageMethod=first 是用来在PageHelper类中判断执行哪个操作
注:mysql中不可以用query.setFirstResult();query.setMaxResults().因为mysql中,不支持selecttop n * from userinfo,支持select * from userinfo limit n;但在sqlserver中可以用。
原创粉丝点击