Struts2 + Hibernate 分页程序实例

时间:2022-03-03 09:34:52

转载自:http://hi.baidu.com/wakin175/blog/item/4d26fef28faf9d14b17ec54e.html

 

1). 针对网上一些 struts2分页的例子 不完整 ,代码混乱繁琐 ,我特意写了一个分页的小例子,供大家参考,如果程序有什么纰漏, 请指出。

开发环境:

eclipse3.2 + myeclipse5.5
mysql5.0
tomcat5.5
Dreamweaver2004

2)建库,并导入脚本

这里给大家介绍一个mysql客户端工具 -- SQLyog ,非常好用。

----------------------------------------------------admin.sql------------------------------------------------

/*
SQLyog Community Edition- MySQL GUI v6.12
MySQL - 5.0.37-community-nt : Database - test

把这段脚本导入到mysql的test库里面(你可以先建一个test库 ,这样会省去很多麻烦)
*************************************************************************/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

create database if not exists `test`;

USE `test`;

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

/*Table structure for table `admin` */

DROP TABLE IF EXISTS `admin`;

CREATE TABLE `admin` (
`id` int(11) NOT NULL auto_increment,
`user` char(20) default NULL,
`pass` char(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;

/*Data for the table `admin` */

insert into `admin`(`id`,`user`,`pass`) values (786432,'天使','#####'),(786433,'天使','#####'),(786434,'天使','#####'),(786435,'天使','#####'),(786436,'天使','#####'),(819200,'天使','#####'),(819201,'天使','#####'),(819202,'天使','#####'),(819203,'天使','#####'),(819204,'天使','#####'),(819205,'wangbacheng','#####'),(851968,'天使','#####'),(851969,'天使','#####'),(851970,'天使','#####'),(851971,'天使','#####'),(851972,'天使','#####');

/*!40101 SET SQL_MODE=@OLD_SQL_MO */;
/*!40014 SET
FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

DE


3)建立数据库连接程序 ,也就是hibernate相关程序,都可以用eclipse自动生成,这个不用多

在eclipse 中只要引入 hibernate核心包和struts2 包 就可以了

Struts2 + Hibernate 分页程序实例

Struts2 + Hibernate 分页程序实例

-------------------------------------------------HibernateSessionFactory.java---------------------------

package action;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see
{@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.  
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

static {
    try {
    configuration.configure(configFile);
    sessionFactory = configuration.buildSessionFactory();
   } catch (Exception e) {
    System.err
      .println("%%%% Error Creating SessionFactory %%%%");
    e.printStackTrace();
   }
    }
    private HibernateSessionFactory() {
    }

/**
     * Returns the ThreadLocal Session instance. Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     * @return Session
     * @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

   if (session == null || !session.isOpen()) {
    if (sessionFactory == null) {
     rebuildSessionFactory();
    }
    session = (sessionFactory != null) ? sessionFactory.openSession()
      : null;
    threadLocal.set(session);
   }

        return session;
    }

/**
     * Rebuild hibernate session factory
     *
     */
public static void rebuildSessionFactory() {
   try {
    configuration.configure(configFile);
    sessionFactory = configuration.buildSessionFactory();
   } catch (Exception e) {
    System.err
      .println("%%%% Error Creating SessionFactory %%%%");
    e.printStackTrace();
   }
}

/**
     * Close the single hibernate session instance.
     *
     * @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

/**
     * return session factory
     *
     */
public static org.hibernate.SessionFactory getSessionFactory() {
   return sessionFactory;
}

/**
     * return session factory
     *
     * session factory will be rebuilded in the next call
     */
public static void setConfigFile(String configFile) {
   HibernateSessionFactory.configFile = configFile;
   sessionFactory = null;
}

/**
     * return hibernate configuration
     *
     */
public static Configuration getConfiguration() {
   return configuration;
}

}

--------------------------------------------------Constants.java--------------------------------------------

package action;

 

public class Constants {
 public static int PAGE_SIZE = 6;
}

--------------------------------------------------Admin.java-----------------------------------------------

package action;

/**
* Admin generated by MyEclipse Persistence Tools
*/

public class Admin implements java.io.Serializable {


    // Fields   

     private Integer id;
     private String user;
     private String pass;


    // Constructors

    /** default constructor */
    public Admin() {
    }

/** minimal constructor */
    public Admin(Integer id) {
        this.id = id;
    }
   
    /** full constructor */
    public Admin(Integer id, String user, String pass) {
        this.id = id;
        this.user = user;
        this.pass = pass;
    }

  
    // Property accessors

    public Integer getId() {
        return this.id;
    }
   
    public void setId(Integer id) {
        this.id = id;
    }

    public String getUser() {
        return this.user;
    }
   
    public void setUser(String user) {
        this.user = user;
    }

    public String getPass() {
        return this.pass;
    }
   
    public void setPass(String pass) {
        this.pass = pass;
    }
  

}

-------------------------------------------------------------Admin.hbm.xml-------------------------------

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="action.Admin" table="admin" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="user" type="java.lang.String">
            <column name="user" length="20" />
        </property>
        <property name="pass" type="java.lang.String">
            <column name="pass" length="20" />
        </property>
    </class>
</hibernate-mapping>
-------------------------------------------------hibernate.cfg.xml------------------------------------------

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
   jdbc:mysql://localhost:3306/test
</property>
<property name="dialect">
   org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">Mysql</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
   com.mysql.jdbc.Driver
</property>
<mapping resource="action/Admin.hbm.xml" />

</session-factory>

</hibernate-configuration>

4).建个工具类,把一些方法封装到里面

--------------------------------------------------PagerHelper.java-----------------------------------------

package action;
import java.util.Collection;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
*
* @author like_dark
* 注意:java包命名的时候不能以 ”java“命名,例如 java.my.xxx ; 真是奇怪啊
*
*/

public class PagerHelper {

public Collection findWithPage(int pageSize, int startRow) throws
HibernateException {
   Collection admins = null;
   Transaction tx = null;
   try {
    Session session = HibernateSessionFactory.getSession();
    tx =   session.beginTransaction() ;
    Query q = session.createQuery("from Admin");
  
    q.setMaxResults(pageSize);
    q.setFirstResult(startRow);
    admins = q.list();
    tx.commit();
   } catch (HibernateException he) {
    if (tx != null) {
     tx.rollback();
    }
    throw he;
   } finally {
    HibernateSessionFactory.closeSession();
   }
   return admins;
}
public int getRows(String query) throws
HibernateException {
   //query : select count(*) from Admin
   int totalRows = 0;
   Transaction tx = null;
   try {
    Session session = HibernateSessionFactory.getSession();
    tx = session.beginTransaction();
    totalRows = ((Integer) session.createQuery(query).list().iterator().next()).intValue() ;
    tx.commit();
   } catch (HibernateException he) {
    if (tx != null) {
     tx.rollback();
    }
    throw he;
   } finally {
    HibernateSessionFactory.closeSession();
   }

   return totalRows;
}

public static void main(String[] args) {
PagerHelper ph = new PagerHelper() ;
System.out.println("rows:"+ph.getRows("select count(*) from Admin")) ;
}

}

5) .struts2相关程序和配置

--------------------------------------------------struts.xml----------------------------------------

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "
http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
   <action name="pager" class="action.PageAction">
    <result name="success">
     /index.jsp
    </result>
    <result name="fail">
     /index.jsp
    </result>
   </action>
</package>
</struts>

----------------------------- PageAction.java ----------------------
package action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PageAction extends ActionSupport {


private int totalRows; //总行数
private int pageSize = Constants.PAGE_SIZE; //每页显示的行数
private int currentPage; //当前页号
private int totalPages; //总页数
private boolean hasNext ; //是否有下一页
private boolean hasPrevious ; //是否有上一页
private Collection CurrentList; //当前数据集
private Collection indexList ; //页码集合

public Collection getCurrentList() {
   return CurrentList;
}

public void setCurrentList(Collection currentList) {
   CurrentList = currentList;
}
/**
* 这里最好用一个引用参数化
*/
public Collection getIndexList() {
  
   ArrayList result = new ArrayList();

   for(int i = 1;i<=getTotalPages();i++){   
            result.add(new Integer(i));
   }
      return result ;
}

public void setIndexList(Collection indexList) {
   this.indexList = indexList;
}

public String execute() throws Exception {
   int totalRows = 0 ;
  
  
   try{

    PagerHelper ph = new PagerHelper() ;
    totalRows =   ph.getRows("select count(*) from Admin") ;    //总行数
    totalPages = (totalRows + pageSize - 1) /pageSize; //总页数
    setIndexList(getIndexList()) ; //生成页码集合
  
    if (currentPage==0 || currentPage<1) {
     first();
    }
            if(currentPage > totalPages){
            last();
            }
            if(currentPage >= 1 && currentPage < totalPages){
            hasNext = true ;
            }
            if(currentPage > 1 && currentPage <= totalPages){
            hasPrevious = true ;
            }
      
/**
* 为了利用session 可以实现SessionAware接口 然后重载 void setSession(Map session) 方法
* action implementation SessionAware{
*      private Map session ;
*      void setSession(Map session){
*         this.session = session ;
*      }
*      session.put(...); session.get(..)
*      或者 继承import com.opensymphony.xwork2.ActionContext;
*      ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession() ;
*/
            CurrentList = ph.findWithPage(Constants.PAGE_SIZE, getStartRow()) ;
    return SUCCESS ;
   }catch(Exception e){
    e.printStackTrace() ;
    return ERROR ;

   }
}

public int getCurrentPage() {
   return currentPage;
}

public void setCurrentPage(int currentPage) {
   this.currentPage = currentPage;
}

public int getPageSize() {
   return pageSize;
}

public void setPageSize(int pageSize) {
   this.pageSize = pageSize;
}

public int getStartRow() {
   if(getCurrentPage() == 1)
    return 0;
   else
      return (getCurrentPage()-1) * pageSize;
}


public int getTotalPages() {
   return totalPages;
}

public void setTotalPages(int totalPages) {
   this.totalPages = totalPages;
}

public int getTotalRows() {
   return totalRows;
}

public void setTotalRows(int totalRows) {
   this.totalRows = totalRows;
}

public void first() { //首页
   currentPage = 1;
   
}

/*public void previous() { //上一页
   if (currentPage == 1) {
    return;
   }
   currentPage--;
}

public void next() {   //下一页
   if (currentPage < totalPages) {
    currentPage++;
   }
}*/

public void last() { //尾页
   currentPage = totalPages;
}

public boolean isHasNext() {
   return hasNext;
}

public void setHasNext(boolean hasNext) {
   this.hasNext = hasNext;
}

public boolean isHasPrevious() {
   return hasPrevious;
}

public void setHasPrevious(boolean hasPrevious) {
   this.hasPrevious = hasPrevious;
}



}
----------------------------struts.properties------------------------------
#struts.custom.i18n.resources=globalMessages
struts.action.extension=do


5) web相关配置和程序
--------------------- web.xml -----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="
http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>
------------------- index.jsp --------------------------------------
<%@ page language="java" contentType="text/html; charset=gb2312"

    pageEncoding="gb2312"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<title>Insert title here</title>
<style type="text/css">
<!--
A:link {
COLOR: #000099; TEXT-DECORATION: none
}
A:visited {
COLOR: #001646; TEXT-DECORATION: none
}
.location {
COLOR: #000000
}
A:active {
COLOR: #ff0000; TEXT-DECORATION: none
}
A:hover {
COLOR: #ff0000; FONT-STYLE: normal; TEXT-DECORATION: underline
}
-->
</style>

</head>

<body>

<s:form action="pager.action">

   <h1>Welcome My Pager</h1><BR>
  
   <hr>

   <!--在这里显示数据-->
<p>UserID   Name   Pass</p>
   <s:iterator value="CurrentList" status="admin">

        <s:property value="id"/>

        <s:property value="user"/>
        <s:property value="pass"/>
        <BR>

   </s:iterator>            

   <!--定义几个动作-->

     <s:url id="url_pre" value="pager.action">

         <s:param name="currentPage" value="currentPage-1"></s:param>

     </s:url>

     <s:url id="url_next" value="pager.action">

         <s:param name="currentPage" value="currentPage+1"></s:param>

     </s:url>

     <s:url id="url_first" value="pager.action">

         <s:param name="currentPage" value="1"></s:param>

     </s:url>

     <s:url id="url_last" value="pager.action">

         <s:param name="currentPage" value="totalPages"></s:param>

     </s:url>

        <!--显示页码 -->
<hr>
第 <s:property value="currentPage"/>/<s:property value="totalPages"/> 页

   <s:a href ="%{url_first}"><font face=webdings >9</font></s:a>

     

   <s:if test="hasPrevious">    

   <s:a href="%{url_pre}"><font face=webdings >7</font></s:a>

   </s:if>
  
    <!--显示数字页码1,2,3,4。。。。 -->
   
   <!--设置两个参数 然后比较是否相等 如果相等 把当前链接加亮 -->  
   <s:set name="currpage" value="<s:property value='currentPage'/>" />
   <s:iterator value="indexList" status="number">     
<!--    <s:set name="listpage" value="<s:property/>" />
  
   <s:if test="#currpage == #listpage">
            Max's file here
   </s:if>
-->
     <!-- <s:url id="url" value="pager.action">

      pass the currentPage parameter 这段代码不能用

         <s:param name="currentPage" value=""></s:param>

      </s:url>
      <s:a href="%{url}">[<s:property/>]</s:a>
     -->
      
     
    <a id="pager_" href="pager.action?currentPage=<s:property/>">[<s:property/>]</a>
    

   </s:iterator>

   <s:if test="hasNext">

   <s:a href="%{url_next}"><font face=webdings >8</font></s:a>

   </s:if>

      <s:a href ="%{url_last}"><font face=webdings >:</font></s:a>

</s:form>  

</body>

</html>

6)。测试

http://localhost:8080/PageDemo/pager.action

Struts2 + Hibernate 分页程序实例


遗留的问题 :我想把我当前的 那个链接页码码加亮 我是这样写的,可是实现不了,如果谁能解决,给我留言,谢谢
            <s:set name="currpage" value="<s:property value='currentPage'/>" />
   <s:iterator value="indexList" status="number">     
   <s:set name="listpage" value="<s:property/>" />
  
   <s:if test="#currpage == #listpage">
             如果当前页是2 那么把2加亮,我就知道是第二页了

   </s:if>
  
   。。。。。。。。。

扩展 :这个程序当页码太多时,比如100 页 美观就是个问题了,掏宝上面那样,只显示几个分页码 ,把中间的部分省略掉,有兴趣的朋友可以试一下。