Struts2提供了一个Spring Plugin插件包,可以使用该插件来管理Struts2的对象创建以及对象的依赖关系。
首先把Struts2包中的struts2-spring-plugin-2.2.1.1.jar、spring-web-2.5.6.jar、 spring-core-2.5.6.jar、spring-context-2.5.6.jar和spring-beans-2.5.6.jar添加到 WEB-INF/lib下。
在web.xml中设置:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
如果你的Spring配置文件名叫applicationContext.xml且放在WEB-INF目录下的话,那么context-param可以不设置。
假设之前的strust.xml中有如下设置:
<action name=”CpAction” ?class=”cn.ricki.cheung.action.CpAction
“>
<result type=”json”/>
</action>
现在由Spring来管理对象,在applicationContext.xml添加如下内容:
<beans>
<bean id=”cpAction
” class=”cn.ricki.cheung.action.CpAction”/>
</beans>
修改strust.xml:
<action name=”CpAction” ?class=”cpAction
“>
<result type=”json”/>
</action>
注意上面黑体显示的部分,在struts.xml中class属性的值为Spring配置文件中某bean id的值,它告诉 Struts2向Spring获取id为cpAction的bean。
其实在上面提到的struts.xml中不只一个Action,除了CpAction外,还有很多,但那些我并没有修改,而程序依然可以运行,原因看下面。
假如struts.xml内容如下:
<action name=”LabelAction” class=”cn.ricki.cheung.action.LabelAction”>
<result type=”json”/>
</action>
<action name=”CpAction” ?class=”cpAction
“>
<result type=”json”/>
</action>
当客户端发送请求并由LabelAction处理时,Struts首先向Spring索取id为
cn.ricki.cheung.action.LabelAction的bean,但Spring配置文件中并没有这个id的bean,这
时,Spring试着创建cn.ricki.cheung.action.LabelActio对象,并返回给Struts。