如何集成Spring和Struts

发表于:2009-3-23 10:24

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:网络转载

  4.使用Spring的ActionSupport类

  要用Spring去集成Struts,创建一个Spring 上下文是必须要做的。 org.springframework.web.struts.ActionSupport 类提供一个 getWebApplicationContext() 方法非常容易地获得Spring上下文,全部你需要去做的是从Spring的ActionSupport 代替Struts 中的Action类去延伸你的action,如下所示:

  package com.infotek.Creditcard.actions;
  import java.io.IOException;
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import org.apache.struts.action.ActionError;
  import org.apache.struts.action.ActionErrors;
  import org.apache.struts.action.ActionForm;
  import org.apache.struts.action.ActionForward;
  import org.apache.struts.action.ActionMapping;
  import org.apache.struts.action.DynaActionForm;
  import org.springframework.context.ApplicationContext;
  import org.springframework.web.struts.ActionSupport;
  import com. infotek.Creditcard.beans.Creditcard;
  import com. infotek.Creditcard.business.CreditcardService;
  public class SearchSubmit extends ActionSupport { |(1)
  public ActionForward execute(ActionMapping mapping,ActionForm form,
  HttpServletRequest request,HttpServletResponse response)
  throws IOException, ServletException {
  DynaActionForm searchForm = (DynaActionForm) form;
  String isbn = (String) searchForm.get("cardno");
  //the old fashion way
  //CreditcardService creditcardService = new CreditcardServiceImpl();
  ApplicationContext ctx = getWebApplicationContext(); |(2)
  CreditcardService creditcardService =
  (CreditcardService ) ctx.getBean("creditcardService"); |(3)
  CreditCard creditard = CreditCardService.read(cardno.trim());
  if (null == creditard) {
  ActionErrors errors = new ActionErrors();
  errors.add(ActionErrors.GLOBAL_ERROR,new ActionError ("message.notfound"));
  saveErrors(request, errors);
  return mapping.findForward("failure") ;
  }
  request.setAttribute("creditcard", creditcard);
  return mapping.findForward("success");
  }
  }

  在(1)中,我们 通过延伸Spring ActionSupport 类而不是Struts Action 类创建了一个action;在(2)中,我们使用getWebApplicationContext()方法获得一个ApplicationContext;为了获得商务服务,在(3)中,我们使用ApplicationContext去查找Spring bean;这个技术非常容易理解,不幸的是它把Struts的action和Spring framework绑定了,如果你想替换Spring你不得不重写代码,而且Struts的action不在Spring的控制之下,遗憾的是这种方法无法获得Spring AOP的好处。

  5.结论

  本文我们尝试使用Spring的ActionSupport,ContextLoaderPlugIn去集成Struts,这是一种最高效的和最简单的方式,另外还可用Spring中的代理子类去代理Struts中的RequestProcessor和代理Struts的actions。

22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号