Chinaunix

标题: Spring Struts整合方案汇总小结 [打印本页]

作者: sunday_jia    时间: 2010-01-14 11:09
标题: Spring Struts整合方案汇总小结



Spring和Struts整合的方案有很多种,整理如下:
第一种 Listener方式
将Spring服务作为web容器的Listener,随web服务器启动而启动
   1、需要在web.xml中配置
Java代码

  •    
  • class>org.springframework.web.context.ContextLoaderListenerclass>   
  •   
    org.springframework.web.context.ContextLoaderListener
       2、然后在Struts的action中通过
    Java代码

  • ServletContext sc = this.getServlet().getServletContext();   
  • WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);   
  • ctx.getBean("xxx");  ServletContext sc = this.getServlet().getServletContext();
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
    ctx.getBean("xxx");
    完成托管Bean的获取。
    第二种 Load on Startup Servlet方式
    将Spring服务作为web容器的load on startup Servlet,随web服务器启动而启动,这种方式和第一种基本是一样的,只是spring加载的时间会比第一种晚一些,servlet2.3标准,listener的加载早于startup servlet的加载
       1、这种方式需要在web.xml中配置
    Java代码

  •    
  • contextLoader   
  • class>org.springframework.web.context.ContextLoaderServletclass>   
  • 1   
  •   
    contextLoader
    org.springframework.web.context.ContextLoaderServlet
    1
       2、这种整合方案,获取bean的方法,和第一种方式相同
    第三种 Struts Plugin+Spring DelegatingRequestProcessor方式
    前两种方式,都没有将struts的action纳入spring管理,接下来的要说的两种方式比较类似,放在一起说明,都是可以将Struts的action纳入到Spring管理的方式。
       1、通过Struts的Plugin方式,在应用启动时加载Spring容器,既然是Struts的Plugin,当然是在struts-xxx.xml文件中进行配置,增加如下Plugin:
    Java代码

  • "org.springframework.web.struts.ContextLoaderPlugIn">   
  • "contextConfigLocation" value="/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext_xxx.xml"/>   
  •   
       2、Struts是通过ActionServlet处理请求的,而代码实现上是通过RequestProcessor进行处理的,通过Spring的RequestProcessor子类-DelegatingRequestProcessor,可以替代原有的Struts请求处理方式,从而转到Spring容器中进行处理。因此需要更改原有的Struts RequestProcessor行为,使用Spring自己的DelegatingRequestProcessor,这需要在struts-xxx.xml中配置,增加如下配置:
    Java代码

  • "org.springframework.web.struts.DelegatingRequestProcessor">  
       3、经过上面的配置,现在struts的action已经交给spring来管理了,spring的DelegatingRequestProcessor会处理web请求,将请求转发给struts-xxx.xml中定义的action,而这些action又是通过spring管理的,因此原来的struts配置文件中的action配置:...中的type就可以省略了,改成...,而type的设置则放到spring的配置文件中,上文中指定了两个spring配置文件/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext_xxx.xml,我们在其中一个文件中加入:
    Java代码

  • "/login" class="com.soar.loginAction" singleton="false">   
  • "xx">   
  •    just a String property   
  •    
  •    
  •   

       just a String property


    这和对待普通的bean没有什么区别了,但是名字是struts配置文件中指定的path指定的值"/login",设置singleton="false"是每请求一次,生成一个action(和struts1默认策略不同)
    这样就完成了spring与struts的整合以及spring管理action


    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/69320/showart_2148617.html




    欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2