收藏 分销(赏)

struts2 hibernate分页.doc

上传人:xrp****65 文档编号:6416697 上传时间:2024-12-08 格式:DOC 页数:22 大小:29.48KB 下载积分:10 金币
下载 相关 举报
struts2 hibernate分页.doc_第1页
第1页 / 共22页
struts2 hibernate分页.doc_第2页
第2页 / 共22页


点击查看更多>>
资源描述
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 包 就可以了 -------------------------------------------------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; } } --------------------------------------------------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.xml------------------------------------------ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" " <!--      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"           " <!-- 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();     mit();    } 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 = ((Long) session.createQuery(query).list().iterator().next()).intValue() ;     mit();    } 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=" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="      <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>     <
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 包罗万象 > 大杂烩

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服