Struts2整合Spring
在此介绍使用Spring的插件(struts2-spring-plug-2.1.6jar)完成整合。
一旦在web应用中安装了插件,便可使用如下的功能:
l 通过Spring来创建所有的Action、Interceptor和Result。
l 可在Struts创建了某个对象之后,Spring将其以来的组件自动注入该对象。
l 提供了两个拦截器来完成自动装配。
步骤如下:
一、 首先使用Spring之前,需要完成Spring的初始化。Struts2提供了两种初始化方式。
1、 利用ContextLoaderListener.
Spring提供了ContextLoaderListener类,该类可作为Struts2的Listener使用,它会在Web应用启动时自动查找WEB-INF下的applicationContext.xml文件,并创建Spring容器。
1.1应用中只有一个spring配置文件且名称为applicationContext.xml时,在web.xml中添加:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener>
1.2 若有多个配置文件,需在1.1的基础之上再添加param参数。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/ WEB-INF/daoContext.xml,/WEB-INF/applicationContext.xml,……(可继续添加,以,隔开)
</context-param>
2、 采用load-on-startup Servlet创建ApplicationContext。如果web服务器不支持Servlet2.3以上的规范,则必须采用本方法创建Spring容器。具体方法此处省略1000个字。
二、 让控制器访问到Spring中的业务逻辑组件。
有两种策略可供选择:
l Spring管理控制器,利用依赖注入为控制器注入逻辑组件。
l 控制器定位Spring工厂。
1、 让Spring管理控制器。
Struts2的核心控制器首先拦截用户请求,然后转发给Action处理,实际上此处的Action由Spring产生,而不是Struts2容器产生,为了将请求转发给Spring中的Action,Spring插件提供了一种伪Action。当在struts.xml中配置action时,其中的class属性,我们不在指定特定的实现类,而是指定spring中的某一BeanID。因此当struts2将请求转发给Action时,此时的action只是一个代号,没有特定的实现类,而真正用来处理事物的action则是Spring容器中的Action。
具体实例:
定义Action类LoginAction.java:
public class LoginAction extends ActionSupport{
private String username;
private String password;
private MYService ms;
set-get方法省略………..
@Override
public Stringexecute() throws Exception {
int user_id=ms.validLogin(username, password);
if(user_id==-1)
return INPUT;
else
return SUCCESS;
}
Struts.xml文件配置action:
<!—注意此处的class只是指定了一个BeanID,没有定位到特定class类-->
<action name="loginAction"class="loginAction">
<result name="input">/jsp/login.jsp</result>
<result name="success">/jsp/success.jsp</result>
<result name="failure">/jsp/login.jsp</result>
</action>
applicationContext.xml文件配置Bean:
<bean id=”loginAction” class=”com.logic.action.LoginAction”>
<property name=”ms” ref=”myService”/>
</bean>
2、 控制器定位spring工厂
使用自动装配的方式,此种方式虽然简化了配置文件的配置,但使得代码的可读性变差并将耦合度提高到了代码层次,不推荐使用此种方式。
还是参照前面的例子。
在struts.xml中,作如下修改:
<action name=”loginAction”class=”com.logic.action.LoginAction”>
……
</action>
Action类代码中的MyService的set方法注意名称,此处为ms:
Public void setMs(MyService ms){
this.ms=ms;
}
在ApplicationContext.xml中部署业务逻辑组件时id属性也必须是ms,与上面一致。
<bean id=”ms” class=”com.logic.service.MyServiceImpl”/>
因为Spring的自动装配策略默认按照name装配,当然可通过在struts.xml中添加变量定义,来改变中配策略,可选项为:
l name
l type
l auto
l constructor
如下:
<content name=”struts.objectFactory.spring.autoWire” value=”type”/>