Spring整合Struts2

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实现类

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值