粗谈Spring与Struts的整合——从实现的Struts的扩展点上看Spring与Struts的整合

来源:互联网 发布:淘宝消保金怎么交 编辑:程序博客网 时间:2024/05/17 06:27

 1.采用DelegatingRequestProcessor将处理转发给Spring容器中的bean

    DelegatingRequestProcessor继承自RequestProcessor。为了让Struts使用DelegatingRequestProcessor,还需要在struts-config.xml文件中增加如下代码:

         <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />

   这一行代码是告诉Struts用DelegatingRequestProcessor来代替原来的RequestProcessor。完成设置这个设置后,Struts会将拦截到的用户请求转发到Spring context下的bean,根据bean的name属性来匹配。而Struts中的action配置则无需配置type属性(即使配置了type属性也不起任何作用)。

   配置了上面的一行代码后,就可以在Spring的配置文件(可以不是applicationContext.xml,比如假设这里是action-servlet.xml)中配置用来处理请求的Action bean了。配置的时候需要注意的是Action bean不再需要id属性,而要用name替代id属性,这时name属性的值应与struts-config.xml中配置的Action的path属性的值相同。

   这样,处理请求的Action就能处于Spring的管理之下了。

2.采用DelegatingActionProxy将处理转发给Spring容器中的bean

   DelegatingRequestProcessor可直接替换原有的RequestProcessor,并在请求转发给action之前,转发给Spring管理的bean;而DelegatingActionProxy则被配置成Struts的action,即所有的请求先被ActionServlet拦截,然后将请求转发给对应的action,而action的实现类全部都是DelegatingActionProxy,最后由DelegatingActionProxy将请求转发给Spring容器中的bean。

   配置时,与采用DelegatingRequestProcessor相比,不再需要struts-config.xml文件中的<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />这行代码,但是Action元素的type属性是必须的,而且是一个定值,都为org.springframework.web.struts.DelegatingActionProxy。Spring配置文件中对用来处理请求的Action bean的配置则无需改变。

3.使用ActionSupport来代替Action

   Spring与Struts的整合也可采用在Action中手动地获得ApplicationContext实例的方法来进行。这种整合策略下,Struts的Action不接受Spring容器的管理,使Action的代码与Spring API部分耦合,也造成了代码的污染。

   Action中访问ApplicationContext有以下两种方法:

      ●利用WebApplicationContextUtils工具类。

      ●利用ActionSupport支持类。

   WebApplicationContext是ApplicationContext的子类。WebApplicationContextUtils可以通过ServletContext获得Spring容器实例。而ActionSupport类则提供了一个更简单的方法:getWebApplicationContext(),该方法用于获取ApplicationContext实例。而且,Spring扩展了Struts的标准Action类,可在其Struts的Action后加上Support,Spring的Action有如下如下几种:

       ●ActionSupport

       ●DispatchActionSupport

       ●LookupDispatchActionSupport

       ●MappingDispatchActionSupport

   采用这种整合策略时,表现层的控制器组件不再受Spring容器的管理,因此没有了控制器context。这种策略下,不需要对Struts及Spring的配置文件有什么特殊的配置。

 

原创粉丝点击