Spring与Struts2整合的两种解决方案

http://www.itzhai.com/spring-and-struts2-integration-of-the-two-solutions.html

Struts2与Spring整合的方案一:
(1)将struts2-spring-plugin-x-x-x.jar复制到工程的WEB-INF/lib目录下,在该插件包中有个struts-plugin.xml文件,该文件的默认配置如下:
<struts>
    <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />

    <!--  Make the Spring object factory the automatic default -->
    <constant name="struts.objectFactory" value="spring" />

    <package name="spring-default">
        <interceptors>
            <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
            <interceptor name="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/>
        </interceptors>
    </package>    
</struts>
(2)在web.xml中配置Spring的监听器:
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext-*.xml</param-value>
</context-param>
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(3)修改Struts.xml配置文件:

在配置Action时,需要将class属性和Spring配置文件中的相对应的Action的bean的Id的属性保持一致,系统即可通过Spring来装配和管理Action。
如果action包含了Service层的对象:

private StudentInfoServiceImpl studentInfoService;

则需要添加set方法,才可以使用Spring依赖注入:

public void setStudentInfoService(StudentInfoServiceImpl studentInfoService) {

	this.studentInfoService = studentInfoService;
}
如果action在struts.xml如下配置:
<action name="studentRegister" class="studentRegisterAction">
	<result name="result">/WEB-INF/exam/result.jsp
	</result>
	<result name="input">/WEB-INF/exam/error.jsp
	</result>
	<interceptor-ref name="excludeParamsStack" />
</action>
则在applicationContext.xml文件中该Action的配置如下:
<bean id="studentRegisterAction" class="com.exam.actions.StudentRegisterAction" scope="prototype">
	<property name="studentInfoService">
		<ref bean="studentInfoService" />
	</property>
</bean>
Struts2与Spring整合的方案二:

前面两个步骤和方案一的一样;
在配置struts.xml文件时,Action的class为该Action的类路径,而在applicationContext.xml配置文件中不需要添加Action的bean配置。这样,当我们使用Action类时,由于studentInfoService已经配置了相关的bean,所以会自动装配。

studentInfoService的配置:
<bean id="studentInfoService" class="com.exam.service.StudentInfoServiceImpl">
	<constructor-arg>
		<ref bean="studentInfoDAO" />
	</constructor-arg>
</bean>
Action在struts.xml中的配置如下:
<action name="studentRegister" class="com.exam.actions.StudentRegisterAction">
	<result name="result">/WEB-INF/exam/result.jsp
	</result>
	<result name="input">/WEB-INF/exam/error.jsp
	</result>
	<interceptor-ref name="excludeParamsStack" />
</action>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值