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

发布于 2011-05-23 | 更新于 2020-09-20

Struts2与Spring整合的方案一:

(1)将struts2-spring-plugin-x-x-x.jar复制到工程的WEB-INF/lib目录下,在该插件包中有个struts-plugin.xml文件,该文件的默认配置如下:

<!\-\-  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>    

(2)在web.xml中配置Spring的监听器:

contextConfigLocation /WEB-INF/applicationContext.xml,/WEB-INF/applicationContext-*.xml org.springframework.web.context.ContextLoaderListener

(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如下配置:

/WEB-INF/exam/result.jsp /WEB-INF/exam/error.jsp

则在applicationContext.xml文件中该Action的配置如下:

Struts2与Spring整合的方案二:

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

studentInfoService的配置:

Action在struts.xml中的配置如下:

/WEB-INF/exam/result.jsp /WEB-INF/exam/error.jsp

本文作者: arthinking

本文链接: https://www.itzhai.comspring-and-struts2-integration-of-the-two-solutions.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。