一个完整的struts2+spring+hibernate+分页实例
前段时间,一直在为配置struts2+spring+hibernate这三大框架头痛。在网上找了很多例子,但都没有解决好我的三大框架的问题。后来把它搁了一段时间。偶尔有一天,我突然想起来了,然后硬着头皮逐字逐字地反复看那几个配置文件,突然我发现,原来犯了个很cheap的错误。敲错了一个字母。导致tomcat启动时老报Error:listenStart...的错误。这个错误可真烦人啊。
以下这个实例在我的机器上运行是没问题的。在此共享一下:
一。 看树:(定位各文件的正确放置)
卷 drfStudy 的文件夹 PATH 列表
卷序列号为 F4AB-013D
E:\ECLIPSEWORKS\PAGING
│ .classpath
│ .myhibernatedata
│ .mymetadata
│ .project
│ .springBeans
│ treeList.txt
│
├─.myeclipse
├─src
│ │ applicationContext-beans.xml
│ │ applicationContext-common.xml
│ │ create.sql
│ │ create.sql.bak
│ │ hibernate.cfg.xml
│ │ instance.txt
│ │ instance.txt.bak
│ │ log4j.properties
│ │ select.sql
│ │ struts.xml
│ │
│ └─cn
│ └─paging
│ ├─action
│ │ ListMemberAction.java
│ │
│ ├─bean
│ │ PageBean.java
│ │
│ ├─dao
│ │ │ MemberDao.java
│ │ │
│ │ └─impl
│ │ MemberDaoImpl.java
│ │
│ ├─model
│ │ Member.hbm.xml
│ │ Member.java
│ │
│ ├─service
│ │ │ MemberService.java
│ │ │
│ │ └─impl
│ │ MemberServiceImpl.java
│ │
│ ├─test
│ └─util
│ HibernateUtils.java
│
└─WebRoot
│ index.jsp
│ list.jsp
│ update.jsp
│
├─META-INF
│ MANIFEST.MF
│
└─WEB-INF
│ spring-form.tld
│ spring.tld
│ web.xml
│
├─classes
│ │ applicationContext-beans.xml
│ │ applicationContext-common.xml
│ │ create.sql
│ │ create.sql.bak
│ │ hibernate.cfg.xml
│ │ instance.txt
│ │ instance.txt.bak
│ │ log4j.properties
│ │ select.sql
│ │ struts.xml
│ │
│ └─cn
│ └─paging
│ ├─action
│ │ ListMemberAction.class
│ │
│ ├─bean
│ │ PageBean.class
│ │
│ ├─dao
│ │ │ MemberDao.class
│ │ │
│ │ └─impl
│ │ MemberDaoImpl.class
│ │
│ ├─model
│ │ Member.class
│ │ Member.hbm.xml
│ │
│ ├─service
│ │ │ MemberService.class
│ │ │
│ │ └─impl
│ │ MemberServiceImpl.class
│ │
│ ├─test
│ └─util
│ HibernateUtils.class
│
└─lib
antlr-2.7.5H3.jar
asm-attrs.jar
asm-commons-2.2.3.jar
asm.jar
aspectjweaver.jar
c3p0-0.9.1.1.jar
cglib-2.1.3.jar
cglib-nodep-2.1_3.jar
commons-attributes-api.jar
commons-attributes-compiler.jar
commons-codec.jar
commons-collections-2.1.1.jar
commons-dbcp.jar
commons-fileupload.jar
commons-io.jar
commons-lang.jar
commons-logging.jar
commons-pool-1.3.jar
concurrent-1.3.2.jar
connector.jar
cos.jar
dom4j-1.6.1.jar
ehcache-1.1.jar
ehcache-1.2.4.jar
freemarker.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate-entitymanager.jar
hibernate3.jar
ibatis-2.3.0.677.jar
jotm.jar
jta.jar
jxl.jar
log4j-1.2.14.jar
mysql-connector-java-5.1.6-bin.jar
ognl-2.6.11.jar
oscache-2.1.jar
spring-agent.jar
spring-aop.jar
spring-beans.jar
spring-context.jar
spring-core.jar
spring-dao.jar
spring-hibernate3.jar
spring-ibatis.jar
spring-jca.jar
spring-jdbc.jar
spring-jdo.jar
spring-jms.jar
spring-jpa.jar
spring-portlet.jar
spring-struts.jar
spring-tomcat-weaver.jar
spring-toplink.jar
spring-web.jar
spring-webmvc.jar
spring.jar
struts2-core-2.0.11.jar
struts2-spring-plugin-2.0.11.2.jar
xapool.jar
xerces-2.6.2.jar
xwork-2.0.4.jar
二。看配置文件(spring,struts,hibernate,web)
(一)spring的配置文件。(在此我用了两个,请对照上面的树放入相应的位置)
1.applicationContext-beans.xml
//**************************************************************************************************
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- action -->
<bean id="listAction" class="cn.paging.action.ListMemberAction" scope="prototype">
<property name="memberService">
<ref local="memberService" />
</property>
<property name="pageBean">
<ref bean="pageBean"/>
</property>
</bean>
<bean id="memberService" class="cn.paging.service.impl.MemberServiceImpl" scope="prototype">
<property name="memberDao">
<ref bean="memberDao"/>
</property>
</bean>
<bean id="memberDao" class="cn.paging.dao.impl.MemberDaoImpl" scope="prototype">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="pageBean" class="cn.paging.bean.PageBean" scope="prototype" >
</bean>
</beans>
//**************************************************************************************************
2.applicationContext-common.xml
//**************************************************************************************************
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- intercept methods -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="list*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution(* cn.paging.service.*.*(..))"/>
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
</aop:config>
</beans>
//**************************************************************************************************
(二)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>
<constant name="struts.objectFactory" value="spring"></constant>
<package name="Paging" extends="struts-default">
<action name="list" class="listAction" method="list" >
<result name="input">index.jsp</result>
<result name="success">/list.jsp</result>
</action>
<action name="edit" class="listAction" method="edit">
<result name="success">/update.jsp</result>
</action>
<action name="update" class="listAction" method="update">
<result type="redirect">list.action</result>
</action>
<action name="add" class="listAction" method="add">
<result type="redirect">list.action</result>
</action>
<action name="delete" class="listAction" method="delete">
<result type="redirect">/list.action</result>
</action>
</package>
</struts>
//**************************************************************************************************
(三)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:2008/test
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">
mysql_Paging
</property>
<property name="connection.password">admin</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="cn/paging/model/Member.hbm.xml" />
</session-factory>
</hibernate-configuration>
//**************************************************************************************************
(四)web.xml文件
//**************************************************************************************************
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
//**************************************************************************************************
三。看数据库mysql,表名Member
//**************************************************************************************************
create table Member
(
id int(11) not null auto_increment primary key,
name varchar(20),
password varchar(100)
)
//**************************************************************************************************
四。看主要代码(以下以包的形式逐一列出)
1.cn.paging.action
ListMemberAction.java
//**************************************************************************************************
package cn.paging.action;
import java.util.Iterator;
import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.opensymphony.xwork2.ActionSupport;
import cn.paging.bean.PageBean;
import cn.paging.model.Member;
import cn.paging.service.MemberService;
import cn.paging.util.HibernateUtils;
public class ListMemberAction extends ActionSupport
{
private MemberService memberService;
private Member member;
private String id;
private static int myId;//keep the id from the link
public void setMemberService(MemberService memberService)
{
this.memberService = memberService;
}
public Member getMember()
{
return member;
}
public void setMember(Member member)
{
this.member = member;
}
private int page; //initial page,default page=1
private PageBean pageBean; //pages information about(all records,list records in per page...)
public int getPage()
{
return page;
}
public void setPage(int page)
{
this.page = page;
}
public PageBean getPageBean()
{
return pageBean;
}
public void setPageBean(PageBean pageBean)
{
this.pageBean = pageBean;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
/**
* list paged records
* @return
* @throws Exception
*/
public String list() throws Exception
{
System.out.println("page="+page);
//list the current page's records,3 records in a page
this.pageBean = memberService.queryForPage(3, page);
return SUCCESS;
}
/**
* edit member for update
* @return string
* @throws Exception
*/
public String edit() throws Exception
{
myId=Integer.parseInt(id);
member = (Member)memberService.edit(Integer.parseInt(id));
return SUCCESS;
}
/**
* update member
* @return string
* @throws Exception
*/
public String update() throws Exception
{
Member m = new Member();
m.setId(myId);
m.setName(member.getName());
m.setPassword(member.getPassword());
memberService.update(m);
return SUCCESS;
}
/**
* add member
* @return string
* @throws Exception
*/
public String add() throws Exception
{
Member m = new Member();
m.setName(member.getName());
m.setPassword(member.getPassword());
memberService.add(m);
return SUCCESS;
}
/**
* delete member
* @return string
* @throws Exception
*/
public String delete()throws Exception
{
memberService.delete(Integer.parseInt(id));
return SUCCESS;
}
}
//**************************************************************************************************
2.cn.paging.bean
PageBean.java
//**************************************************************************************************
package cn.paging.bean;
import java.util.List;
public class PageBean
{
private List list;
private int allRow; //all records
private int totalPage;
private int currentPage;
private int pageSize; //records in per page
private boolean isFirstPage;
private boolean isLastPage;
private boolean hasPreviousPage;
private boolean hasNextPage;
public List getList()
{
return list;
}
public void setList(List list)
{
this.list = list;
}
public int getAllRow()
{
return allRow;
}
public void setAllRow(int allRow)
{
this.allRow = allRow;
}
public int getTotalPage()
{
return totalPage;
}
public void setTotalPage(int totalPage)
{
this.totalPage = totalPage;
}
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;
}
/**
* initial paging information
*/
public void init()
{
this.isFirstPage = isFirstPage();
this.isLastPage = isLastPage();
this.hasPreviousPage = isHasPreviousPage();
this.hasNextPage = isHasNextPage();
}
public boolean isFirstPage()
{
return currentPage == 1;
}
public boolean isLastPage()
{
return currentPage == totalPage;
}
public boolean isHasPreviousPage()
{
return currentPage != 1;
}
public boolean isHasNextPage()
{
return currentPage != totalPage;
}
public static int countTotalPage(final int pageSize, final int allRow)
{
int totalPage = allRow % pageSize == 0 ? allRow / pageSize : allRow
/ pageSize + 1;
return totalPage;
}
public static int countOffset(final int pageSize, final int currentPage)
{
final int offset = pageSize * (currentPage - 1);
return offset;
}
public static int countCurrentPage(int page)
{
final int curPage = (page == 0 ? 1 : page);
return curPage;
}
}
//**************************************************************************************************
3.cn.paging.dao
MemberDao.java
//**************************************************************************************************
package cn.paging.dao;
import java.util.List;
public interface MemberDao
{
/**
* query for paging
* @param hql (string expression)
* @return records
*/
public List queryForPage(final String hql,final int offset,final int length);
/**
* query all records
* @param hql (string expression)
* @return total records
*/
public int getAllRowCount(String hql);
/**
* update record
* @param o (object that mapping your class's name in model)
*
*/
public void update(Object o);
/**
* add record
* @param o
*/
public void add(Object o);
/**
* delete record
*
* @param id (delete record by id)
*/
public void delete(int id);
/**
* edit record for update
* @param id (edit it by id)
* @return object
*/
public Object edit(int id);
}
//**************************************************************************************************
4.cn.paging.dao.impl
MemberDaoImpl.java
//**************************************************************************************************
package cn.paging.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import cn.paging.dao.MemberDao;
import cn.paging.model.Member;
import cn.paging.util.HibernateUtils;
public class MemberDaoImpl extends HibernateDaoSupport implements MemberDao
{
/**
* query for paging
* @param hql (string expression)
* @param offset (first record)
* @param length (the quantity of record in per page)
* @return list (for paging in a page)
*/
public List queryForPage(final String hql, final int offset,
final int length)
{
Query query = HibernateUtils.getSession().createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
List list = query.list();
return list;
}
/**
* query all records
* @return the number of total records
*/
public int getAllRowCount(String hql)
{
int result = 0;
result = HibernateUtils.getSession().createQuery(hql).list().size();
return result;
}
/**
* edit for update
* @param id (edit by id)
*/
public Object edit(int id)
{
System.out.println("memberdaoimpl edit id=" + id);
Query query = HibernateUtils.getSession().createQuery(
"from Member m where m.id=:id ").setInteger("id", id);
return query.iterate().next();
}
/**
* update record by object
* @param o (add record by object)
*/
public void update(Object o)
{
Session session = HibernateUtils.getSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
session.update(o);
Member m = (Member) o;
tx.commit();
System.out.println("memberDoaImpl updateOrSave Object.name="
+ m.getName());
System.out.println("memberDoaImpl updateOrSave Object.password="
+ m.getPassword());
System.out.println("memberDoaImpl updateOrSave Object.id="
+ m.getId());
}
catch (HibernateException e)
{
e.printStackTrace();
tx.rollback();
}
finally
{
HibernateUtils.closeSession(HibernateUtils.getSession());
}
System.out.println("memberDoaImpl updateOrSave success");
}
/**
* add record
* @param o (add record by object)
*/
public void add(Object o)
{
Session session = HibernateUtils.getSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
session.save(o);
Member m = (Member) o;
tx.commit();
System.out.println("memberDoaImpl updateOrSave Object.name="
+ m.getName());
System.out.println("memberDoaImpl updateOrSave Object.password="
+ m.getPassword());
System.out.println("memberDoaImpl updateOrSave Object.id="
+ m.getId());
}
catch (HibernateException e)
{
e.printStackTrace();
tx.rollback();
}
finally
{
HibernateUtils.closeSession(HibernateUtils.getSession());
}
System.out.println("memberDoaImpl add success");
}
/**
* delete record
* @param id (delete record by id)
*/
public void delete(int id)
{
Session session = HibernateUtils.getSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
// String hql="delete from Member m where m.id=:id";
// int queryDelete=HibernateUtils.getSession().createQuery("delete from Member m where m.id=:id")
// .setInteger("id", id)
// .executeUpdate();
Member m = (Member) session.get(Member.class, id);
session.delete(m);
tx.commit();
System.out.println("MemberDaoImpl delete id=" + id);
}
catch (HibernateException e)
{
e.printStackTrace();
tx.rollback();
}
finally
{
HibernateUtils.closeSession(HibernateUtils.getSession());
}
System.out.println("memberDoaImpl delete");
}
}
//**************************************************************************************************
5.cn.paging.model
Member.java
//**************************************************************************************************
package cn.paging.model;
public class Member
{
private int id;
private String name;
private String password;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
//**************************************************************************************************
Member.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="cn.paging.model.Member" table="member" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="20" not-null="true" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="100" />
</property>
</class>
</hibernate-mapping>
//**************************************************************************************************
6. cn.paging.service
MemberService.java
//**************************************************************************************************
package cn.paging.service;
import cn.paging.bean.PageBean;
public interface MemberService
{
public PageBean queryForPage(int pageSize, int currentPage);
<span s