Struts 2整合Spring


 SpringjavaEE领域一个非常优秀的框架,它的主要核心是IoCInversion of Control,控制反转)容器和AOP机制。

 

大部分JavaEE应用,都会考虑使用Spring容器来管理应用中的组件,从而保证各组件之间的低耦合。Struts 2框架只是一个MVC框架,只是一个Web层的解决方案,如果不与其他框架整合将会严重影响Struts 2框架功能的发挥。Struts 2通过一种“可插拔式”的插件,实现了与Spring框架的整合。

    

一、添加jar

spring.jardest路径下,这个文件是Spring框架最全的类库,添加该文件比使用分模块类库更加简单)、commos-loggin.jar复制Web应用的WEB-INF/lib路径下。

    安装Struts 2Spring插件:将Struts2-spring-plugin-2.3.1.2.jar复制到WEB-INF/lib路径下。

 

二、Spring容器的初始化

    在web.xml文件中增加下一段:

    <!--根据默认配置文件来初始化Spring容器-->

    <listener>

       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

 

     如果应用中的Spring配置文件有多个,则应该采用如下形式的web.xml文件来创建Spring容器。 

<!--指定多个Spring的配置文件-->

<context-param>

  <param-name>contextConfigLocation</param-name>

    <!--多个配置文件之间以,隔开-->

  <param-value>classpath*:/conf/spring.mvc.xml,/WEB-INF/applicationContext.xml</param-value>

</context-param>

<listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

 

    如果没有在web.xml中利用contextConfigLocation指定配置文件,则Spring自动查找WEB-INF路径下的“applicationContext.xml”配置文件。如果无法找到合适的配置文件,Spring将无法正常初始化。

 

 

三、整合流程

    Spring插件提供了一种伪Action,当我们在struts.xml文件中配置Action时,通常需要指定class属性,该属性就是用于创建Action实例的实现类。但Spring插件允许我们知道class属性时,不是指向Action的实际实现类,而是指向Spring容器中的BeanID。整合后的组件协作如图所示:

 

 

在这种整合策略下,处理用户请求的ActionSpring插件负责创建,但Spring插件创建Action实例时,并不是利用配置Action时指定的class属性来创建该Action实例的,而是从Spring容器中取出对应的Bean实例完成创建的。

 

例如在struts.xml中配置action

     <!--ActionSpring负责创建,此处的class属性不是实际处理类 -->

    <atcion name=login class=loginBean>

      <result name=welcome>/WEB-INF/welcome.jsp</result>

    </action>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值