深入探讨 Spring 与 Struts 的集成方案(2)

23 篇文章 0 订阅
13 篇文章 0 订阅
2.注册Spring插件:为了使Struts Action能够访问由Spring管理的Bean,我们就必须要注册一个知道Spring应用上下文的Struts插件.可以在struts-config.xml中通过如下的方式来完成注册.  
< plug-in classname="org.springframework.web.struts.ContextLoadPlugin">
  < set-property value="WEB-INF/Yhcip.xml,......" property="contextConfigLocation">
  < /PLUG-IN>
  ContextLoadPlugin()负责装载一个Spring应用上下文.(具体的说:是一个WebApplicationContext).value属性值为要加载的配置Spring受控Bean的xml文件的URI.

  3.完成第一种集成方案:实现一个知晓Spring的Action基类.

  这种集成方案是从一个公共的能够访问Spring应用上下文的基类中派生所有的Struts Action,但值得庆幸的是:我们不用自己去编写这个知晓Spring应用上下文的基类,因为Spring已经提供了org.springframework.web.struts.ActionSupport:一个org.apache.struts.action.Action的抽象实现.它重载了setServlet()方法以从ContextLoaderPlugin中获取WebapplicationContext.因此,任何时候我们只需要调用super.getBean()方法即可获得一Spring上下文中的一个Bean的引用.

  我们再来看一段Action源代码:  

public class CourceAction extends ActionSupport {
  public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) throws Exception {
  //取得Spring上下文
  ApplicationContext context = super.getWebApplicationContext();
  //取得CourceService Bean
  CourseService courseService = (CourseService) context.getBean("courseService");
  Set allCources = courceService.getAllCources(); request.setAttribute("cources", allCources);
  //..........the other statements.
  return mapping.findForward("jspView");
  }}
  分析:这个Action类由ActionSupport派生,当CourceAction需要一个Spring受控Bean时:它首先调用基类的getWebApplicationContext()方法以取得一个Spring应用上下文的引用;接着它调用getBean()方法来获取由Spring管理的courceService Bean的一个引用.

  小结

  至此,我们已经用第一种方案圆满的完成了Spring与Struts的集成工作.这种集成方式的好处在于直观简洁容易上手.除了需要从ActionSupport中派生,以及需要从应用上下文中获取Bean之外,其他都与在非Spring的Struts中编写和配置Action的方法相似.但这种集成方案也有不利的一面.最为显著的是:我们的Action类将直接使用Spring提供的特定类,这样会使我们的Struts Action(即控制层)的代码与Spring紧密耦合在一起.这是我们不情愿看到的.另外,Action类也负责查找由Spring管理的Bean,这违背了反向控制(IoC)的原则.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值