1>整合Struts2使用Spring和单独使用Spring有所不同,首先,启动Spring容器的方式就不一样,对于使用Spring的web应用,无须手动创建Spring容器,而是通过配置文件声明式的创建Spring容器。在Web容器中创建Spring容器有两种方式:
1>直接在Web配置文件中配置创建Spring容器
2>利用第三方MVC框架的扩展点创建Spring容器
其中第一种方式更为常见,在Web配置文件中配置创建Spring容器借助于ServletContextListener监听类完成,该监听类可以在web应用启动时回调自定义方法,该自定义方法可以启动Spring容器。Spring本身提供了该监听类的一个实现类ContextLoaderListener,该类可以作为监听使用,它会在创建时自动查找WEB-INF/下的applicationContext.xml文件:
//web配置文件配置该监听类片段
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
该监听类默认查找/web-inf/applicationContext.xmlSpring配置文件,如果我们需要查找其他的配置文件或者需要查找多个配置文件,可以使用元素通过配置contextConfigLocation属性来配置文件名:
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>spring.xml</param-value>
</context-param>
</listener>
<listener-class>org.springframework.web.context.ContextLoaderLocation</listener-class>
</listener>
</web-app>
如果需要在应用中创建Spring容器,可以使用如下代码:
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext) ;
2>添加Struts整合Spring的插件:struts2-spring-plugin.jar
3>之前使用Action时,是在Struts配置文件中完全配置Action的全部信息,现在整合Spring后,配置Action的任务就有Spring和Struts来共同完成了。配置Action的方式:Struts配置Action依旧,只是class属性不再是该Action的实现类,而是Spring配置的对应的该Action实现类的Bean的id/name,而在Spring中就将该Action对应的实现类配置成SpringBean,然后两者相对应起来。如:
//struts.xml
<struts>
<package ...>
<action name="login" class="loginbean">
<result...>...</result>
...
</action>
</package>
</struts>
//spring.xml
<beans...>
<bean id="loginbean" class="LoginAction" />
</beans>
//web.xml
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.config.ContextLoaderListener</listener-class>
</listener>
</web-app>
整合的流程为:用户(提交请求) –> Struts2核心控制器(转发请求) –> 伪控制器 (对应) –> 实际控制器(Spring容器中伪控制器对应的spring bean实现类