如何集成Spring和Struts (二)

本文介绍如何使用Spring的ActionSupport类来集成Struts框架。通过继承Spring的ActionSupport类并利用getWebApplicationContext()方法获取Spring上下文,可以方便地实现Struts与Spring的集成。但这种方式将Struts action与Spring绑定,若更换框架则需重构代码。

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值