Spring整合Struts2



Spring整合Struts2以下介绍几个配置部分的配置,这几个部分配置好了,也就可以了,先上工程图
Spring整合Struts2

一、配置web.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/beans.xml</param-value>
  </context-param>
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
     
 <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>*.action</url-pattern>
 </filter-mapping>

以上主要配置spring为随着服务器启动而自启动,配置struts2过滤器,配置spring配置文件的位置

二、action类代码

public class LoginAction {
   LoginService loginService;
   public LoginService getLoginService() {
       return loginService;
   }
   public void setLoginService(LoginService loginService) {
       this.loginService = loginService;
   }
   public String execute() throws Exception {
       loginService.hello();
       return “success”;
   }
}
LoginService 为要注入的对象,需有set方法


三、spring配置文件beans.xml
   <bean id=”loginService”></bean>
   <bean id=”login” scope=”prototype”>
   <property name=”loginService” ref=”loginService”/>
   </bean>
这里名为login的bean是struts2中的action,由spring负责action的创建,在该action中
设置loginService属性

四、struts2的配置文件
<constant name=”struts.objectFactory” value=”org.apache.struts2.spring.StrutsSpringObjectFactory” /> 
<include file=”struts-default.xml”></include>
<package name=”" extends=”struts-default” namespace=”/mm”>
<action name=”login”>
<result name=”success”>/success.jsp</result>
</action>
</package>

以上指定了对象工厂为StrutsSpringObjectFactory,这样struts2的action就不再又struts2而是由spring
负责产生了
另外action元素中的class属性不再指向其实际的class,而是指向beans.xml中某个action bean的id

测试:http://localhost:8080/SS2H/mm/login.action
这样就完成了两者的整合

另外要注意的是要导入好所需要的jar包,比如struts2的spirng插件包,spring的web包