Chinaunix首页 | 论坛 | 博客
  • 博客访问: 419275
  • 博文数量: 79
  • 博客积分: 2886
  • 博客等级: 少校
  • 技术积分: 968
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-16 10:33
文章分类

全部博文(79)

文章存档

2013年(7)

2012年(17)

2011年(28)

2010年(25)

2009年(1)

2008年(1)

我的朋友

分类: Java

2010-01-14 11:09:38

 

Spring和Struts整合的方案有很多种,整理如下:

第一种 Listener方式
将Spring服务作为web容器的Listener,随web服务器启动而启动
   1、需要在web.xml中配置
Java代码 复制代码
  1.   
  2. class>org.springframework.web.context.ContextLoaderListenerclass>   
  3.   

   2、然后在Struts的action中通过
Java代码 复制代码
  1. ServletContext sc = this.getServlet().getServletContext();   
  2. WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);   
  3. 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代码 复制代码
  1.   
  2. contextLoader   
  3. class>org.springframework.web.context.ContextLoaderServletclass>   
  4. 1   
  5.   

   2、这种整合方案,获取bean的方法,和第一种方式相同

第三种 Struts Plugin+Spring DelegatingRequestProcessor方式
前两种方式,都没有将struts的action纳入spring管理,接下来的要说的两种方式比较类似,放在一起说明,都是可以将Struts的action纳入到Spring管理的方式。
   1、通过Struts的Plugin方式,在应用启动时加载Spring容器,既然是Struts的Plugin,当然是在struts-xxx.xml文件中进行配置,增加如下Plugin:
Java代码 复制代码
  1. "org.springframework.web.struts.ContextLoaderPlugIn">   
  2. "contextConfigLocation" value="/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext_xxx.xml"/>   
  3.   

   2、Struts是通过ActionServlet处理请求的,而代码实现上是通过RequestProcessor进行处理的,通过Spring的RequestProcessor子类-DelegatingRequestProcessor,可以替代原有的Struts请求处理方式,从而转到Spring容器中进行处理。因此需要更改原有的Struts RequestProcessor行为,使用Spring自己的DelegatingRequestProcessor,这需要在struts-xxx.xml中配置,增加如下配置:
Java代码 复制代码
  1. "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代码 复制代码
  1. "/login" class="com.soar.loginAction" singleton="false">   
  2.  "xx">   
  3.    just a String property   
  4.     
  5.     
  6.   

这和对待普通的bean没有什么区别了,但是名字是struts配置文件中指定的path指定的值"/login",设置singleton="false"是每请求一次,生成一个action(和struts1默认策略不同)
这样就完成了spring与struts的整合以及spring管理action
阅读(669) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~