1:首先必须要注意的是不能在struts2的action中直接调用继承hibernateSupport的DAO,不然好多东西无法初始化,会抛出:java.lang.NULLException.在action中只能初始话的是从页面传过来的数据。而action必须要调用业务逻辑层来完成具体的工作。
所以应该有这么个模式:
1:让spring管理所有的bean。hibernate的datasource sessionFactory。还有我们自己的具体dao,这里要注意我们的dao必须要引用sessionFactory,所以要把sessionFactory注入到我们的dao中由我们自己的dao借助sessionFactory 产生的hibernateTemplate来完成具体共组。
HibernateDaoSupport 已经为我们注入好了sessionFactory.
接着我们要定义业务逻辑层,然后把业务逻辑bean由spring管理。因为业务逻辑需要dao,所以把我们的dao注入到业务逻辑层,我们的业务逻辑层把需要的一些东西都弄好。然后我们把struts2的action的class交给spring管理,然后在这个bean中注入action需要的逻辑bean.
具体示例:
1web.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"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<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>
</webapp>
2:applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost/quser" />
<property name="user" value="root" />
<property name="password" value="123" />
<property name="maxPoolSize" value="20" />
<property name="minPoolSize" value="1" />
<property name="initialPoolSize" value="1" />
<property name="maxIdleTime" value="20" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>qdns/feng/dao/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
</props>
</property>
</bean>
<bean id="LoginAction" class="qdns.feng.action.LoginAction">
<property name="userManager" ref="userManager"></property>
</bean>
<bean id="RegistAction" class="qdns.feng.action.RegistAction">
<property name="userManager" ref="userManager"></property>
</bean>
<bean id="userManager" class="qdns.feng.dao.UserManager">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="qdns.feng.dao.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory"></ref>
</property>
</bean>
</beans>
3: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.i18n.encoding" value="utf-8" />
<constant name="struts.objectFactory" value="spring" />
<package name="qiandu" extends="json-default">
<global-results>
<!-- 下面定义的结果对所有的Action都有效 -->
<result name="exception">/error.jsp</result>
<result name="success">/success.jsp</result>
</global-results>
<global-exception-mappings>
<!-- 指Action抛出Exception异常时,转入名为exception的结果。 -->
<exception-mapping exception="java.lang.Exception"
result="exception" />
</global-exception-mappings>
<action name="regist" class="RegistAction">
<result name="success">/success.jsp</result>
</action>
<action name="registpage">
<result>/shop/regist1.jsp</result>
</action>
<action name="login" class="qdns.feng.action.LoginAction">
<result name="success">/success.jsp</result>
<result name="input">/shop/login.jsp</result>
</action>
</package>
</struts>
5:具体应用程序demo
1:userDAO
package qdns.feng.dao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
* A data access object (DAO) providing persistence and search support for User
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see qdns.feng.dao.User
* @author MyEclipse Persistence Tools
*/
public class UserDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(UserDAO.class);
// property constants
public static final String USER_NAME = "userName";
public static final String USER_PASSWORD = "userPassword";
public static final String USER_QQ = "userQq";
public static final String USER_PHONE = "userPhone";
protected void initDao() {
// do nothing
}
public void save(User transientInstance) {
log.debug("saving User instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(User persistentInstance) {
log.debug("deleting User instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public User findById(java.lang.Integer id) {
log.debug("getting User instance with id: " + id);
try {
User instance = (User) getHibernateTemplate().get(
"qdns.feng.dao.User", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(User instance) {
log.debug("finding User instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding User instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from User as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByUserName(Object userName) {
return findByProperty(USER_NAME, userName);
}
public List findByUserPassword(Object userPassword) {
return findByProperty(USER_PASSWORD, userPassword);
}
public List findByUserQq(Object userQq) {
return findByProperty(USER_QQ, userQq);
}
public List findByUserPhone(Object userPhone) {
return findByProperty(USER_PHONE, userPhone);
}
public List findAll() {
log.debug("finding all User instances");
try {
String queryString = "from User";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = (User) getHibernateTemplate().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(User instance) {
log.debug("attaching dirty User instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(User instance) {
log.debug("attaching clean User instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
return (UserDAO) ctx.getBean("UserDAO");
}
}
2:userManager
package qdns.feng.dao;
import java.util.List;
public class UserManager {
private UserDAO userDao;
public void setUserDao(UserDAO userDao){
this.userDao = userDao;
}
public int addUser(String userName , String userPassword , String userPhone,String userQq)
throws Exception{
try{
User u = new User();
u.setUserName(userName);
u.setUserPassword(userPassword);
u.setUserPhone(userPhone);
u.setUserQq(userQq);
userDao.save(u);
return u.getUserId();
}
catch (Exception e){
e.printStackTrace();
throw new Exception("新增用户时出现异常");
}
}
public int loginValid(String userName , String userPassword)
throws Exception
{
try
{
List u =userDao.findByUserName(userName);
if (u != null)
{
return 2;
}
}
catch (Exception e)
{
e.printStackTrace();
throw new Exception("验证用户登陆时出现异常");
}
return -1;
}
}
RegisterAction.java
package qdns.feng.action;
import java.util.Map;
import qdns.feng.dao.UserManager;
import com.opensymphony.xwork2.ActionSupport;
public class RegistAction extends ActionSupport {
private String userName;
private String userPassword;
private String userQq;
private String userPhone;
private UserManager userManager;
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserQq() {
return userQq;
}
public void setUserQq(String userQq) {
this.userQq = userQq;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
@Override
public String execute() throws Exception{
if(userManager.addUser(userName, userPassword, userPhone, userQq)>0){
System.out.println("终于成功!");
return SUCCESS;
}else{
System.out.println("出错了");
return "input";
}
}
}