俯瞰Struts2的整体流程

来源:互联网 发布:mac 安装lnmp 编辑:程序博客网 时间:2024/04/29 08:35
俯瞰Struts2的整体流程 〖 作者:Struts2BBS 〗〖 大小:2K 〗〖 发布日期:2008-04-16 〗〖 浏览:0 〗 在第1章中,已经介绍了MVC设计思想和Struts 2框架的实现。而Struts 2框架本身大致可以分为3个部分:核心控制器FilterDispatcher、业务控制器Action和用户实现的企业业务逻辑组件。3.1.1 核心控制器FilterDispatcher核心控制器FilterDispatcher是Struts 2框架的基础,包含了框架内部的控制流程和处理机制。业务控制器Action和业务逻辑组件是需要用户来自己实现的。用户在开发Action和业务逻辑组件的同时,还需要编写相关的配置文件,供核心控制器FilterDispatcher来使用。Struts 2的工作流程相对于Struts 1要简单,与WebWork框架基本相同,所以说Struts 2是WebWork的升级版本。Struts 2框架按照模块来划分,可以分为Servlet Filters、Struts核心模块、拦截器和用户实现部分。Struts 2框架结构图如图3.1所示。 图3.1 Struts 2框架结构图一个请求在Struts 2框架中的处理大概分为以下几个步骤。 客户端提交一个(HttpServletRequest)请求,如上文在浏览器中输入http://localhost: 8080/bookcode/ch2/Reg.action就是提交一个(HttpServletRequest)请求。 请求被提交到一系列(主要是3层)的过滤器(Filter),如(ActionContextCleanUp、其他过滤器(SiteMesh等)、 FilterDispatcher)。注意:这里是有顺序的,先ActionContext CleanUp,再其他过滤器(Othter Filters、SiteMesh等),最后到FilterDispatcher。 FilterDispatcher是控制器的核心,就是MVC的Struts 2实现中控制层(Controller)的核心。 FilterDispatcher询问ActionMapper是否需要调用某个Action来处理这个(HttpServlet Request)请求,如果ActionMapper决定需要调用某个Action,FilterDispatcher则把请求的处理交给ActionProxy。 ActionProxy通过Configuration Manager(struts.xml)询问框架的配置文件,找到需要调用的Action类。例如,用户注册示例将找到UserReg类。 ActionProxy创建一个ActionInvocation实例,同时ActionInvocation通过代理模式调用Action。但在调用之前,ActionInvocation会根据配置加载Action相关的所有Interceptor(拦截器)。 一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果result。Struts 2的核心控制器是FilterDispatcher,有3个重要的方法:destroy()、doFilter()和Init(),可以在Struts 2的下载文件夹中找到源代码,如代码3.1所示。代码3.1 核心控制器FilterDispatcherpublic class FilterDispatcher implements StrutsStatics, Filter { /** * 定义一个Log实例 */private static final Log LOG = LogFactory.getLog(FilterDispatcher.class);… ... /** * 存放属性文件中的.STRUTS_I18N_ENCODING值 */ private static String encoding; /** * 定义ActionMapper实例 */ private static ActionMapper actionMapper; /** * 定义FilterConfig实例 */ private FilterConfig filterConfig; protected Dispatcher dispatcher; /** * 创建一个默认的dispatcher,初始化filter * 设置默认的packages * */ public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; dispatcher = createDispatcher(filterConfig); dispatcher.init(); String param = filterConfig.getInitParameter("packages"); String packages = "org.apache.struts2.static template org.apache.struts2.interceptor.debugging"; if (param != null) { packages = param + " " + packages; } this.pathPrefixes = parse(packages); } //销毁filter方法 public void destroy() { if (dispatcher == null) { LOG.warn("something is seriously wrong, Dispatcher is not initialized (null) "); } else { dispatcher.cleanup(); } } /** * 处理一个Action或者资源请求 *

* filter尝试将请求同action mapping相匹配 * 如果找到,将执行dispatcher的serviceAction方法 * 如果Action处理失败, doFilter将建立一个异常 *

* 如果请求静态资源 * 资源将被直接复制给 response *

* 如果找不到匹配Action 或者静态资源,则直接跳出 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ServletContext servletContext = getServletContext(); String timerKey = "FilterDispatcher_doFilter: "; try { UtilTimerStack.push(timerKey); request = prepareDispatcherAndWrapRequest(request, response); ActionMapping mapping; try { mapping=actionMapper.getMapping(request, dispatcher.getConfigurationManager()); } catch (Exception ex) { LOG.error("error getting ActionMapping", ex); dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex); return; } if (mapping == null) { String resourcePath = RequestUtils.getServletPath(request); if ("".equals(resourcePath) && null != request.getPathInfo()) { resourcePath = request.getPathInfo(); } if (serveStatic && resourcePath.startsWith("/struts")) { String name = resourcePath.substring("/struts".length()); findStaticResource(name, request, response); } else { //为一个普通的request, 则通过 chain.doFilter(request, response); } return; }/***这个方法询问ActionMapper是否需要调用某个Action来处理这个(request)请求,*如果ActionMapper决定需要调用某个Action,*FilterDispatcher则把请求的处理交给ActionProxy dispatcher.serviceAction(request, response, servletContext, mapping); } finally { try { ActionContextCleanUp.cleanUp(req); } finally { UtilTimerStack.pop(timerKey); } }}… …}在doFilter()方法中,将调用dispatcher.serviceAction,该方法如果找到相应的Action,将把用户请求交给ActionProxy。serviceAction()代码在Dispatcher.java中,如代码3.2所示。代码3.2 Dispatcher类public class Dispatcher {.../** * 为mapping加载类,并调用相应的方法或者直接返回result *

* 根据用户请求的参数,建立Action上下文 * 根据指定的Action’名称和包空间名称,加载一个Action代理 ActionProxy * 然后Action的相应方法将被执行, */ public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping) throws ServletException { Map extraContext = createContextMap(request, response, mapping, context); //如果存在一个值栈,则建立一个新的并复制以备Action使用 ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY); if (stack!= null) { extraContext.put(ActionContext.VALUE_STACK, ValueStackFactory.getFactory().createValueStack(stack)); } String timerKey = "Handling request from Dispatcher"; try { UtilTimerStack.push(timerKey); String namespace = mapping.getNamespace(); String name = mapping.getName(); String method = mapping.getMethod(); Configuration config = configurationManager.getConfiguration(); //FilterDispatcher把请求的处理交给ActionProxy ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(namespace, name, extraContext, true, false); proxy.setMethod(method); request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); //ActionMapping 直接返回一个result if (mapping.getResult() != null) { Result result = mapping.getResult(); result.execute(proxy.getInvocation()); } else { proxy.execute(); } if (stack != null) { request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack); } } catch (ConfigurationException e) { LOG.error("Could not find action or result", e); sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e); } catch (Exception e) { throw new ServletException(e); } finally { UtilTimerStack.pop(timerKey); } }…}从上面代码中可以看出来,Struts 2用于处理用户请求的Action实例,并不是用户实现的业务控制器,而是Action代理。关于Action代理相关内容,读者可以参考拦截器章节的介绍。★ 提示 ★前面一直在说Action可以是一个普通的Java类,与Servlet API完全分离,但是为了实现业务逻辑,Action需要使用HttpServletRequest内容。Struts 2设计的精巧之处就是使用了Action代理,Action代理可以根据系统的配置,加载一系列的拦截器,由拦截器将HttpServletRequest参数解析出来,传入Action。同样,Action处理的结果也是通过拦截器传入HttpServletResponse,然后由HttpServletRequest传给用户。其实,该处理过程是典型的AOP(面向切面编程)的方式,读者可以在后面详细了解到。Struts 2处理过程模型如图3.2所示。 图3.2 Struts 2处理过程模型★ 说明 ★拦截器是Struts 2框架的核心,通过拦截器,实现了AOP(面向切面编程)。使用拦截器,可以简化Web开发中的某些应用,例如,权限拦截器可以简化Web应用中的权限检查。3.1.2 业务控制器Action业务控制器Action是由开发者自己编写实现的,Action类可以是一个简单的Java类,与Servlet API完全分离。Action一般都有一个execute()方法,也可以定义其他业务控制方法,详细内容将在后面介绍。Action的execute()返回一个String类型值,这与Struts 1返回的ActionForward相比,简单易懂。Struts 2提供了一个ActionSupport工具类,该类实现了Action接口和validate()方法,一般开发者编写Action可以直接继承ActionSupport类。编写Action类后,开发者还必须在配置文件中配置Action。一个Action的配置应该包含下面几个元素:1、该Action的name,即用户请求所指向的URL。2、Action所对应的class元素,对应Action类的位置。3、指定result逻辑名称和实际资源的定位。Action是业务控制器,笔者建议在编写Action的时候,尽量避免将业务逻辑放到其中,尽量减少Action与业务逻辑模块或者组件的耦合程度。3.1.3 业务模型组件业务模型组件可以是实现业务逻辑的模块,可以是EJB、POJO或者JavaBean,在实际开发中,对业务模型组件的区分和定义也是比较模糊的,实际上也超出了Struts 2框架的范围。不同的开发者或者团队,都有自己的方式来实现业务逻辑模块,Struts 2框架的目的就是使用Action来调用业务逻辑模块。例如一个银行存款的业务逻辑模块,如代码3.3所示。代码3.3 模拟一个银行业务的实现模块package ch3;public class Bank { //定义银行账户 private String accounts; //定义操作金额 private double money; //属性的getter和setter方法 public String getAccounts() { return accounts; } public void setAccounts(String accounts) { this.accounts = accounts; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } //模拟银行存款方法 public boolean saving(String accounts, double money) { //调用DAO等模块读写数据库 return dosomeing(); }}上面实例在实际开发中没有任何意义,这里只是作为业务逻辑模块来说明,在执行saving(String accounts,double money)方法时,可以调用相应的数据库访问其他组件,来实现存款操作。使用Action调用该业务逻辑组件可以在execute()方法中实现,如代码3.4所示。 代码3.4 业务控制器Bank_Saving_Actionpackage ch3;import java.util.Map;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class Bank_Saving_Action extends ActionSupport { //定义银行账户 private String accounts; //定义操作金额 private double money; public String execute() throws Exception { //创建Bank实例 Bank bk=new Bank(); //调用存款方法 if (bk.saving(accounts, money)){ return SUCCESS; }else{ return ERROR; }} //属性的getter和setter方法 public String getAccounts() { return accounts; } public void setAccounts(String accounts) { this.accounts = accounts; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; }Bank_Saving_Action演示了对银行存款业务逻辑组件的调用,这里是通过在Action中创建业务逻辑组件实例的方式实现的。在实际开发中,可以使用静态工厂获得业务逻辑组件的实例或者使用IoC容器来管理。Action中不实现任何业务逻辑,只是负责组织调度业务逻辑组件。调用关系如图3.3所示。 图3.3 调用业务逻辑组件★ 说明 ★业务控制器Action一般情况下不是直接创建业务逻辑组件实例,而是使用工厂模式或者是从Spring容器中获得业务逻辑组件实例,这样可以提高系统的性能。3.1.4 视图组件Struts 1只能支持JSP作为视图资源,而Struts 2的进步之处就是可以使用其他视图技术,如FreeMarker、Velocity等。通过前面的学习和示例,读者会知道Action的返回结果只是一个简单的字符串,也就是一个逻辑上的视图名称,要与实际视图资源对应,必须通过配置文件来实现。 在struts.xml配置文件中,每一个Aciton定义都有name和class属性,同时还要指定result元素。result元素指定了逻辑视图名称和实际视图的对应关系。每个result都有一个type属性,前面介绍的struts.xml中并没有显式指定type值,即使用了默认的type类型:dispatcher,该结果类型支持JSP所谓视图资源。 对于Struts 2的视图技术和result返回类型,后面将详细介绍。

原创粉丝点击