1、1). 针对网上一些 struts2分页的例子 不完整 ,代码混乱繁琐 ,我特意写了一个分页的小例子,供大家参考,如果程序有什么纰漏, 请指出。 开发环境: eclipse3.2 + myeclipse5.5 mysql5.0 tomcat5.5 Dreamweaver2004 2)建库,并导入脚本 这里给大家介绍一个mysql客户端工具 -- SQLyog ,非常好用。 ----------------------------------------------------admin.sql-------------------------------------------
2、 /* 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 databa
3、se 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`
4、 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,'天使','####
5、'),(786435,'天使','#####'),(786436,'天使','#####'),(819200,'天使','#####'),(819201,'天使','#####'),(819202,'天使','#####'),(819203,'天使','#####'),(819204,'天使','#####'),(819205,'wangbacheng','#####'),(851968,'天使','#####'),(851969,'天使','#####'),(851970,'天使','#####'),(851971,'天使','#####'),(851972,'天使','#####');
6、 /*!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--------------
7、 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 * pat
8、tern, 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 cl
9、asspath 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 ThreadLo
10、cal
11、re(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadL
12、ocal Session instance. Lazy initialize
* the SessionFactory if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (se
13、ssion == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate ses
14、sion factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.pr
15、intStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null);
16、if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebu
17、ilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configur
18、ation; } } --------------------------------------------------Admin.java-------------------------------------------------- package action; /** * Admin generated by MyEclipse Persistence Tools */ public class Admin implements java.io.Serializable { // Fields private Integer
19、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, Str
20、ing 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 getUs
21、er() { 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; } } --------------------------
22、Admin.xml------------------------------------------
24、length="20" />
25、
27、oot
28、 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“命名,例如 jav
29、a.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.beginTransa
30、ction() ; 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 { Hibernate
31、SessionFactory.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 = sessio
32、n.beginTransaction(); totalRows = ((Long) session.createQuery(query).list().iterator().next()).intValue() ; mit(); } catch (HibernateException he) { if (tx != null) { tx.rollback(); } throw he; } finally { HibernateSessionFactory.closeSession(); }
33、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----------------------------------------
34、
36、va.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;
37、 //当前页号 private int totalPages; //总页数 private boolean hasNext ; //是否有下一页 private boolean hasPrevious ; //是否有上一页 private Collection CurrentList; //当前数据集 private Collection indexList ; //页码集合 public Collection getCurrentList() { return CurrentList; } public void setCurrentList(Collection c
38、urrentList) { 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(C
39、ollection 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)
40、 /pageSize; //总页数 setIndexList(getIndexList()) ; //生成页码集合 if (currentPage==0 || currentPage<1) { first(); } if(currentPage > totalPages){ last(); } if(currentPage >= 1 && currentPage < totalPages){ hasNext = t
41、rue ; } if(currentPage > 1 && currentPage <= totalPages){ hasPrevious = true ; } /** * 为了利用session 可以实现SessionAware接口 然后重载 void setSession(Map session) 方法 * action implementation SessionAware{ * private Map session ; * void
42、 setSession(Map session){ * this.session = session ; * } * session.put(...); session.get(..) * 或者 继承import com.opensymphony.xwork2.ActionContext; * ActionContext ctx = ActionContext.getContext(); Map session = ctx.getSession() ; */ CurrentList =
43、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; }
44、 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() { retu
45、rn 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
46、void previous() { //上一页 if (currentPage == 1) { return; } currentPage--; } public void next() { //下一页 if (currentPage < totalPages) { currentPage++; } }*/ public void last() { //尾页 currentPage = totalPages; } public boolean isHasNext() { return hasNext;
47、 } public void setHasNext(boolean hasNext) { this.hasNext = hasNext; } public boolean isHasPrevious() { return hasPrevious; } public void setHasPrevious(boolean hasPrevious) { this.hasPrevious = hasPrevious; } } ----------------------------struts.properties-----------------
48、
#struts.custom.i18n.resources=globalMessages
struts.action.extension=do
5) web相关配置和程序
--------------------- web.xml -----------------------------------
49、a-instance" xsi:schemaLocation="






