使用Spring更好地处理Struts动作

http://tech.ddvip.com   2006年11月20日    社区交流

本文详细介绍使用Spring更好地处理Struts动作

  使用 Spring 的 ActionSupport 类整合 Structs 使用 Spring 的 DelegatingRequestProcessor 覆盖 Struts 的 RequestProcessor 将 Struts Action 管理委托给 Spring 框架   装载应用程序环境

  无论您使用哪种技术,都需要使用 Spring 的 ContextLoaderPlugin 为 Struts 的 ActionServlet 装载 Spring 应用程序环境。就像添加任何其他插件一样,简单地向您的 struts-config.xml 文件添加该插件,如下所示:

<plug-in className=
 "org.springframework.web.struts.ContextLoaderPlugIn">
  <set-property property=
   "contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>

  每个例子都为一个书籍搜索应用程序提供一种不同的 Struts 和 Spring 的整合方法。您可以在这里看到例子的要点,但是您也可以下载应用程序以查看所有的细节。

  窍门 1. 使用 Spring 的 ActionSupport

  手动创建一个 Spring 环境是一种整合 Struts 和 Spring 的最直观的方式。为了使它变得更简单,Spring 提供了一些帮助。为了方便地获得 Spring 环境,org.springframework.web.struts.ActionSupport 类提供了一个 getWebApplicationContext() 方法。您所做的只是从 Spring 的 ActionSupport 而不是 Struts Action 类扩展您的动作,如清单 1 所示:

  清单 1. 使用 ActionSupport 整合 Struts

package ca.nexcel.books.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 ca.nexcel.books.beans.Book;
import ca.nexcel.books.business.BookService;
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("isbn");
 
  //the old fashion way
  //BookService bookService = new BookServiceImpl();
 
  ApplicationContext ctx = 
   getWebApplicationContext();  |(2)
  BookService bookService = 
   (BookService) ctx.getBean("bookService");  |(3)
    
 Book book = bookService.read(isbn.trim());
  if (null == book) {
   ActionErrors errors = new ActionErrors();
   errors.add(ActionErrors.GLOBAL_ERROR,new ActionError
    ("message.notfound"));
   saveErrors(request, errors);
   return mapping.findForward("failure") ;
 }
  request.setAttribute("book", book);
  return mapping.findForward("success");
 }
}

  让我们快速思考一下这里到底发生了什么。在 (1) 处,我通过从 Spring 的 ActionSupport 类而不是 Struts 的 Action 类进行扩展,创建了一个新的 Action。在 (2) 处,我使用 getWebApplicationContext() 方法获得一个 ApplicationContext。为了获得业务服务,我使用在 (2) 处获得的环境在 (3) 处查找一个 Spring bean。

来源:ibm    作者:George Franciscus    责编:豆豆技术应用

正在加载评论...