---
title: "偷窥struts+hibernate分页(第一种方法) "
author: "box1106"
date: "2009-02-09T17:09:56Z"
tags: []
slug: "struts-hibernate"
draft: false
lastmod: "2009-02-09T17:09:56Z"
id: 325795
url: "https://box1106.iteye.com/blog/325795"
---

## [偷窥struts+hibernate分页(第一种方法)](http://www.blogjava.net/wujun/archive/2006/08/29/65890.html)

根据原文有点改动。原文忘记在那里看到了。看到提个醒

新建表

DROP DATABASE IF EXISTS \`wjcms\`;  
CREATE DATABASE \`wjcms\` /\*!40100 DEFAULT CHARACTER SET gb2312 \*/;  
USE \`wjcms\`;

\#  
# Table structure for table t\_article  
\#

CREATE TABLE \`t\_article\` (  
  \`a\_id\` int(11) NOT NULL auto\_increment,  
  \`a\_sort\` int(11) NOT NULL default '0',  
  \`a\_title\` varchar(50) default NULL,  
  \`a\_body\` text,  
  \`a\_author\` varchar(11) default '',  
  \`a\_hit\` int(11) NOT NULL default '0',  
  \`c\_id\` int(11) default '0',  
  \`a\_date\` varchar(20) default NULL,  
  PRIMARY KEY  (\`a\_id\`)  
) 

实体

public class articleVO {  
    private int a\_id;  
    private int a\_sort;  
    private int a\_hit;  
    private int c\_id;  
    private String a\_title;  
    private String a\_body;  
    private String a\_author;  
    private String a\_date;  
    // getter setter

新建page.java

package page.dal;

public class page {  
    private int totalRows; //总行数  
    private int pageSize = 10; //每页显示的行数  
    private int currentPage; //当前页号  
    private int totalPages; //总页数  
    private int startRow; //当前页在数据库中的起始行

    public page(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();  
     }  
   }

 }

新建 pageHelp.java

package page.dal;  
import javax.servlet.http.\*;

public class PagerHelp {  
    public static page getPager(HttpServletRequest httpServletRequest,int totalRows) {

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

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

     //如果当前页号为空，表示为首次查询该页  
     //如果不为空，则刷新page对象，输入当前页号等信息  
     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;  
   }

}

新建 util.java

package page.dal;  
import net.sf.hibernate.Query;  
import net.sf.hibernate.cfg.Configuration;  
import java.util.List;  
import net.sf.hibernate.HibernateException;  
import net.sf.hibernate.SessionFactory;  
import net.sf.hibernate.Session;  
import java.util.\*;  
public class util {  
    public util() {  
    }  
     private Session ss=null;  
    public Session getSession()  
  {  
      //  Configuration config=null;  
      SessionFactory sessionFactory;  
      try {  
          Configuration cfg = new Configuration();  
          sessionFactory = cfg.addClass(articleVO.class).  
                           buildSessionFactory();  
          // SessionFactory sessionFactory=config.buildSessionFactory();  
          ss = sessionFactory.openSession();  
          return ss;  
      } catch (HibernateException ex) {  
          System.out.print("getsession出错了。。" + ex.getMessage());  
          return null;  
      }  
  }

  public int getCount()  
  {  
      String sql="select count(\*) from articleVO" ;  
      this.getSession();

    try {  
     // ss.createQuery("select count(a)as cont from articleVO a ");  
      int rows= ((Integer) ss.iterate(sql).next()).intValue();  
      ss.flush();  
      return rows;

    } catch (HibernateException ex) {  
        System.out.print("ex::"+ex.getMessage());  
        return 0;  
    }

  }

  public Collection  getList(int pagesize,int currow) throws HibernateException {  
      Collection vehicleList = null;  
      this.getSession();  
      Query q=ss.createQuery("from articleVO");  
      q.setFirstResult(currow);  
      q.setMaxResults(pagesize);  
      vehicleList=q.list();  
      ss.flush();  
      return vehicleList;  
  }

}

新建 struts  PageAction.java

package page.dal;

import org.apache.struts.action.ActionMapping;  
import org.apache.struts.action.ActionForm;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.apache.struts.action.ActionForward;  
import org.apache.struts.action.Action;  
import page.dal.\*;  
import java.util.\*;  
import net.sf.hibernate.\*;

public class pageAction extends Action {  
    public ActionForward execute(ActionMapping mapping, ActionForm form,  
                                 HttpServletRequest request,  
                                 HttpServletResponse response) {  
        Collection clInfos = null;//用于输出到页面的记录集合  
        int totalRows;//记录总行数  
        util dal=new util();  
        totalRows=dal.getCount();  
        System.out.print("总行数=="+totalRows);  
        page p=PagerHelp.getPager(request,totalRows);  
        try {  
            clInfos = dal.getList(p.getPageSize(), p.getStartRow());

        } catch (HibernateException ex) {  
            System.out.print("action里的错误="+ex.getMessage());  
        }  
        request.setAttribute("page",p);  
        request.setAttribute("list",clInfos);  
        return mapping.findForward("page");  
        //pageForm pageForm = (pageForm) form;  
      //  throw new java.lang.UnsupportedOperationException(  
              //  "Method $execute() not yet implemented.");  
    }  
}

前台页面

&lt;%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %&gt;  
&lt;%@ taglib uri="/WEB-INF/struts-nested.tld" prefix="nested" %&gt;  
&lt;%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %&gt;  
&lt;%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %&gt;  
&lt;%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %&gt;  
&lt;%@ page contentType="text/html; charset=GBK" %&gt;  
&lt;html:html&gt;  
&lt;head&gt;  
&lt;title&gt;  
page  
&lt;/title&gt;  
&lt;/head&gt;  
&lt;body&gt;  
&lt;table align="center" border="2"&gt;  
&lt;tr&gt;  
&lt;th&gt;a\_title&lt;/th&gt;  
&lt;th&gt;a\_body&lt;/th&gt;  
&lt;th&gt;a\_a\_date&lt;/th&gt;  
&lt;th&gt;a\_author&lt;/th&gt;  
&lt;/tr&gt;

&lt;logic:iterate id="listd" name="list"&gt;  
&lt;tr&gt;  
&lt;td&gt;  
&lt;bean:write name="listd" property="a\_title"/&gt;  
&lt;/td&gt;  
&lt;td&gt;  
&lt;bean:write name="listd" property="a\_author"/&gt;  
&lt;/td&gt;  
&lt;td&gt;  
&lt;bean:write name="listd" property="a\_date"/&gt;  
&lt;/td&gt;  
&lt;td&gt;  
&lt;bean:write name="listd" property="a\_date"/&gt;  
&lt;/td&gt;  
&lt;/tr&gt;  
&lt;/logic:iterate&gt;

&lt;/table&gt;

第&lt;bean:write name="page" property="currentPage"/&gt;页  
共&lt;bean:write name="page" property="totalPages" /&gt;页  
&lt;html:link action="/pageAction.do?pageMethod=first"  
paramName="page" paramProperty="currentPage" paramId="currentPage"&gt;首页&lt;/html:link&gt;  
   &lt;html:link action="/pageAction.do?pageMethod=previous"  
paramName="page" paramProperty="currentPage" paramId="currentPage"&gt;上一页&lt;/html:link&gt;  
   &lt;html:link action="/pageAction.do?pageMethod=next"  
paramName="page" paramProperty="currentPage" paramId="currentPage"&gt;下一页&lt;/html:link&gt;

   &lt;html:link action="/pageAction.do?pageMethod=last"  
paramName="page" paramProperty="currentPage" paramId="currentPage"&gt;尾页&lt;/html:link&gt;  
&lt;/body&gt;  
&lt;/html:html&gt;

启动浏览 pageAction.do  运行OK。

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

配置文件

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!DOCTYPE hibernate-mapping PUBLIC  
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"&gt;  
&lt;hibernate-mapping&gt;

    &lt;class name="page.dal.articleVO" table="t\_article" &gt;

    &lt;id name="a\_id" column="a\_id" unsaved-value="0" &gt;  
      &lt;generator class="native"/&gt;  
 &lt;/id&gt;  
     &lt;property name="c\_id"    column="c\_id"/&gt;  
     &lt;property name="a\_title" column="a\_title"/&gt;  
     &lt;property name="a\_sort"  column="a\_sort"/&gt;  
     &lt;property name="a\_date"  column="a\_date"/&gt;  
     &lt;property name="a\_body"  column="a\_body"/&gt;  
     &lt;property name="a\_hit"   column="a\_hit"/&gt;  
     &lt;property name="a\_author" column="a\_author"/&gt;  
     
      
  &lt;/class&gt;

&lt;/hibernate-mapping&gt;

hibernate.dialect net.sf.hibernate.dialect.MySQLDialect  
hibernate.connection.driver\_class org.gjt.mm.mysql.Driver  
hibernate.connection.url jdbc:mysql://localhost:3306/wjcms  
hibernate.connection.username root  
hibernate.connection.password   
hibernate.connection.pool\_size 1  
hibernate.proxool.pool\_alias pool1  
hibernate.show\_sql true  
hibernate.max\_fetch\_depth 1  
hibernate.cache.use\_query\_cache true