步骤:
1,导入struts2的相关jar包(检查是否有冲突的包,即同一个包有不同的几个版本存在)
2,导入struts2和spring的整合包 struts2-spring-plugin-2.3.4.jar
3,配置struts.xml文件(打开struts2的用户向导帮助可以找到如何集成spring)
<!-- 表示action由Spring创建,可以直接使用spring的依赖注入来做 --> <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
4, 创建Action
/** * 此时等于用Spring创建了userAction对象,在struts.xml配置文件中写action的class的时候 * 就不能写类,而应该写userAction这个对象 */ @Controller("userAction")
5,重新配置struts.xml基于通配符的访问方式
<!-- 基于通配符的方式 ,由于整合了Spring,在class中不用使用完整的类,而应该使用spring所注入的对象,如userAction就应该使用userAction来创建 --> <action name="*_*" class="{1}Action" method="{2}"> <result>/WEB-INF/{1}/{2}.jsp</result> <result name="input">/WEB-INF/jsp/{1}/{2}Input.jsp</result> <result type="redirect" name="redirect">/${url}</result> </action>
6, 在web.xml中配置获取BeanFactory的操作
1)创建监听器获取Spring的工厂
<!-- 1,创建Spring的监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 2, Spring的监听器通过context-param获取beans.xml的位置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:beans.xml</param-value> </context-param>
2)配置Struts2的过滤器
<!-- 3,配置struts2的过滤器--> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
7,下面是一个完整过程的代码
1)beans.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--1, 打开Spring的annotation --> <context:annotation-config/> <!-- 2, 设定Spring去那些包中找annotation --> <context:component-scan base-package="com.yangw.spring" /> <!-- 使用dbcp没有成功, 加的是commons-dbcp-1.4.jar class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <context:property-placeholder location="classpath:jdbc.properties"/> <!--创建sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" > <!-- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" --> <property name="dataSource" ref="dataSource"/> <!-- 基于XML配置文件的形式 <property name="mappingResources"> <list> <value>product.hbm.xml</value> </list> </property> --> <!-- 自动去包中找hbm文件或者设置了annotation的类--> <property name="packagesToScan" value="com.yangw.spring.model" /> <!-- 将hibernate配置文件放到单独的配置文件中的方式--> <!-- <property name="configLocation" value="classpath:hibernate.cfg.xml" /> --> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update hibernate.format_sql=false </value> </property> </bean> <!-- 配置Spring事务处理 --> <!-- 1,创建事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 2, 配置AOP,Spring是通过AOP进行事务管理的--> <aop:config> <!-- 设置PointCut表示哪些方法要加入事务--> <aop:pointcut id="allMethods" expression="execution(* com.yangw.spring.dao.*.*(..))"/> <!-- 通过advisor来确定具体加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods"/> </aop:config> <!--3, 配置哪些方法要加入事务 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="count*" read-only="true" /> <tx:method name="is*" read-only="true" /> <tx:method name="has*" read-only="true" /> <!-- 所有方法都加入事务 --> <tx:method name="*" /> </tx:attributes> </tx:advice> </beans>
2) 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.action.extension" value="action,do" /> <constant name="struts.configuration.xml.reload" value="true" /> <constant name="struts.multipart.maxSize" value="10240000" /> <constant name="struts.custom.i18n.resources" value="Message" /> <!-- 表示action由Spring创建,可以直接使用spring的依赖注入来做 --> <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" /> <package name="default" extends="struts-default"> <!-- 基于通配符的方式 --> <action name="*_*" class="{1}Action" method="{2}"> <result>/WEB-INF/jsp/{1}/{2}.jsp</result> <result name="input">/WEB-INF/jsp/{1}/{2}Input.jsp</result> <result type="redirect" name="redirect">/${url}</result> </action> </package> </struts>
3)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- 1,创建Spring的监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 2, Spring的监听器通过context-param获取beans.xml的位置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:beans.xml</param-value> </context-param> <!-- 3,配置struts2的过滤器--> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
4)UserAction
package com.yangw.spring.action; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.yangw.spring.model.User; import com.yangw.spring.service.IUserService; /** * 此时等于用Spring创建了userAction对象,在struts.xml配置文件中写action的class的时候 * 就不能写类,而应该写userAction这个对象 * @author Administrator * */ @Controller("userAction") @Scope("prototype") public class UserAction extends ActionSupport implements ModelDriven<User> { private User user; @Resource private IUserService userService; public User getModel() { if(user==null) user=new User(); return user; } public String list(){ ActionContext.getContext().put("userList", userService.list()); return SUCCESS; } }
5) IUserService 和 UserService
package com.yangw.spring.service; import java.util.List; import com.yangw.spring.model.User; public interface IUserService { public void add(User user); public void update(User user); public void delete(int id) ; public User load(int id); public List<User> list(); }
package com.yangw.spring.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.yangw.spring.dao.IUserDao; import com.yangw.spring.model.User; @Service("userService") public class UserService implements IUserService { @Resource private IUserDao userDao; public void add(User user) { userDao.add(user); } public void update(User user) { userDao.update(user); } public void delete(int id) { userDao.delete(id); } public User load(int id) { return userDao.load(id); } public List<User> list() { String hql="from User"; return userDao.list(hql); } }
6) IUserDao 和 UserDao
package com.yangw.spring.dao; import com.yangw.spring.model.User; public interface IUserDao extends IBaseDao<User>{ //此时的IUserDao只需要写特殊的一些方法,让子类去实现 //假设下面这个是IUserDao中的特殊方法 public void add(User user,int gid); }
package com.yangw.spring.dao; import org.springframework.stereotype.Repository; import com.yangw.spring.model.User; @Repository("userDao") public class UserDao extends BaseDao<User> implements IUserDao { public void add(User user, int gid) { System.out.println("cccc"); } }
7) IBaseDao 和 BaseDao
package com.yangw.spring.dao; import java.util.List; /** * IBaseDao接口是所有Dao公共的操作 * @author Administrator * @param <T> */ public interface IBaseDao<T> { public void add(T t); public void update(T t); public void delete(int id); public T load(int id); public List<T> list(String hql,Object[] args); public List<T> list(String hql); public List<T> list(String hql,Object arg); }
package com.yangw.spring.dao; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * * 把所有公共方法都写到BaseDao,所有Dao都继承 BaseDao即可,这样就实现了大量的基础方法 * 如果Dao中有特殊的方法,再次具体的Dao中进行实现 * @author Administrator * * @param <T> */ public class BaseDao<T> extends HibernateDaoSupport implements IBaseDao<T> { //注入SessionFactory @Resource(name="sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory){ super.setSessionFactory(sessionFactory); } private Class<T> entityClass; /** * 获取T对象的Class * @return */ @SuppressWarnings({ "unused", "unchecked" }) private Class<T> getEntityClass(){ if(entityClass==null){ entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } return entityClass; } public void add(T t) { super.getHibernateTemplate().save(t); } public void update(T t) { super.getHibernateTemplate().update(t); } public void delete(int id) { //先加载对象再删除 super.getHibernateTemplate().delete(this.load(id)); } public T load(int id) { return super.getHibernateTemplate().get(getEntityClass(), id); } @SuppressWarnings("unchecked") public List<T> list(String hql, Object[] args) { //select * 的处理,可以利用反射来做 Query query=this.getSession().createQuery(hql); if(args!=null){ for(int i=0;i<args.length;i++){ query.setParameter(i, args[i]); } } return query.list(); } public List<T> list(String hql) { return this.list(hql, null); } public List<T> list(String hql, Object arg) { return this.list(hql, new Object[]{arg}); } }
8) /WEB-INF/jsp/user/list.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <s:iterator value="#userList"> ---${id}-----${name}----${age}---<br/> </s:iterator> </body> </html>