1、Struts2的工作机制分析及实例 一、概述 本章讲述Struts2的工作原理。 读者如果曾经学习过Struts1.x或者有过Struts1.x的开发经验,那么千万不要想当然地以为这一章可以跳过。实际上Struts1.x与Struts2并无我们想象的血缘关系。虽然Struts2的开发小组极力保留Struts1.x的习惯,但因为Struts2的核心设计完全改变,从思想到设计到工作流程,都有了很大的不同。 Struts2是Struts社区和WebWork社区的共同成果,我们甚至可以说,Struts2是WebWork的升级版,他采用的正是WebWork的核心,所以,Struts2
2、并不是一个不成熟的产品,相反,构建在WebWork基础之上的Struts2是一个运行稳定、性能优异、设计成熟的WEB框架。 本章主要对Struts的源代码进行分析,因为Struts2与WebWork的关系如此密不可分,因此,读者需要下载xwork的源代码,访问 下载的Struts2源代码文件是一个名叫struts-2.1.0-src.zip的压缩包,里面的目录和文件非常多,读者可以定位到struts-2.1.0-src\struts-2.0.10\src\core\src\main\java目录下查看Struts2的源文件,如图14所示。 (图14) 二、
3、 主要的包和类 Struts2框架的正常运行,除了占核心地位的xwork的支持以外,Struts2本身也提供了许多类,这些类被分门别类组织到不同的包中。从源代码中发现,基本上每一个Struts2类都访问了WebWork提供的功能,从而也可以看出Struts2与WebWork千丝万缕的联系。但无论如何,Struts2的核心功能比如将请求委托给哪个Action处理都是由xwork完成的,Struts2只是在WebWork的基础上做了适当的简化、加强和封装,并少量保留Struts1.x中的习惯。 以下是对各包的简要说明: 包名 说明 org.apache.struts2. comp
4、onents 该包封装视图组件,Struts2在视图组件上有了很大加强,不仅增加了组件的属性个数,更新增了几个非常有用的组件,如updownselect、doubleselect、datetimepicker、token、tree等。 另外,Struts2可视化视图组件开始支持主题(theme),缺省情况下,使用自带的缺省主题,如果要自定义页面效果,需要将组件的theme属性设置为simple。 org.apache.struts2. config 该包定义与配置相关的接口和类。实际上,工程中的xml和properties文件的读取和解析都是由WebWork完成的,Struts只
5、做了少量的工作。 org.apache.struts2.dispatcher Struts2的核心包,最重要的类都放在该包中。 org.apache.struts2.impl 该包只定义了3个类,他们是StrutsActionProxy、StrutsActionProxyFactory、StrutsObjectFactory,这三个类都是对xwork的扩展。 org.apache.struts2.interceptor 定义内置的截拦器。 org.apache.struts2.util 实用包。 org.apache.struts2.validators 只定义了一个类:D
6、WRValidator。 org.apache.struts2.views 提供freemarker、jsp、velocity等不同类型的页面呈现。 下表是对一些重要类的说明: 类名 说明 org.apache.struts2.dispatcher. Dispatcher 该类有两个作用: 1、初始化 2、调用指定的Action的execute()方法。 org.apache.struts2.dispatcher. FilterDispatcher 这是一个过滤器。文档中已明确说明,如果没有经验,配置时请
7、将url-pattern的值设成/*。 该类有四个作用: 1、执行Action 2、清理ActionContext,避免内存泄漏 3、处理静态内容(Serving static content) 4、为请求启动xwork’s的截拦器链。 com.opensymphony.xwork2. ActionProxy Action的代理接口。 com.opensymphony.xwork2. ctionProxyFactory 生产ActionProxy的工厂。 com.open
8、symphony.xwork2.ActionInvocation 负责调用Action和截拦器。 com.opensymphony.xwork2.config.providers. XmlConfigurationProvider 负责Struts2的配置文件的解析。 三、 Struts2的工作机制 3.1 Struts2体系结构图 Strut2的体系结构如图15所示: (图15) 3.2 Struts2的工作机制 从图15可以看出,一个请求在Struts2框架中的处理
9、大概分为以下几个步骤: 1、客户端初始化一个指向Servlet容器(例如Tomcat)的请求; 2、这个请求经过一系列的过滤器(Filter)(这些过滤器中有一个叫做ActionContextCleanUp的可选过滤器,这个过滤器对于Struts2和其他框架的集成很有帮助,例如:SiteMesh Plugin); 3、接着FilterDispatcher被调用,FilterDispatcher询问ActionMapper来决定这个请求是否需要调用某个Action; 4、如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交给Act
10、ionProxy; 5、ActionProxy通过Configuration Manager询问框架的配置文件,找到需要调用的Action类; 6、ActionProxy创建一个ActionInvocation的实例。 7、ActionInvocation实例使用命名模式来调用,在调用Action的过程前后,涉及到相关拦截器(Intercepter)的调用。 8、一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。返回结果通常是(但不总是,也可能是另外的一个Action链)一个需要被表示的JSP或者FreeMarker的模版
11、在表示的过程中可以使用Struts2 框架中继承的标签。在这个过程中需要涉及到ActionMapper。
注:以上步骤参考至网上,具体网址已忘记。在此表示感谢!
3.3 Struts2源代码分析
和Struts1.x不同,Struts2的启动是通过FilterDispatcher过滤器实现的。下面是该过滤器在web.xml文件中的配置:
代码清单6:web.xml(截取)
12、 org.apache.struts2.dispatcher.FilterDispatcher
13、 实际上,FilterDispatcher除了实现Filter接口以外,还实现了StrutsStatics接口,继承代码如下: 代码清单7:FilterDispatcher结构 public class FilterDispatcher implements StrutsStatics, Filter { } StrutsStatics并没有定义业务方法,只定义了若干个常量。Struts2对常用的接口进行了重新封装,比如HttpServletRequest、HttpServletResponse、HttpServletContext等。 以下是StrutsStati
14、cs的定义: 代码清单8:StrutsStatics.java public interface StrutsStatics { /** * Constant for the HTTP request object. */ public static final String HTTP_REQUEST = "com.opensymphony.xwork2.dispatcher.HttpServletRequest"; /** * Constant for the HTTP response object.
15、 */ public static final String HTTP_RESPONSE = "com.opensymphony.xwork2.dispatcher.HttpServletResponse"; /** * Constant for an HTTP request dispatcher}. */ public static final String SERVLET_DISPATCHER = "com.opensymphony.xwork2.dispatcher.ServletDispatcher"; /**
16、 * Constant for the servlet context} object. */ public static final String SERVLET_CONTEXT = "com.opensymphony.xwork2.dispatcher.ServletContext"; /** * Constant for the JSP page context}. */ public static final String PAGE_CONTEXT = "com.opensymphony.xwork2.dispatcher
17、PageContext"; /** Constant for the PortletContext object */ public static final String STRUTS_PORTLET_CONTEXT = "struts.portlet.context"; } 容器启动后,FilterDispatcher被实例化,调用init(FilterConfig filterConfig)方法。该方法创建Dispatcher类的对象,并且将FilterDispatcher配置的初始化参数传到对象中(详情请参考代码清单10),并负责Actio
18、n的执行。然后得到参数packages,值得注意的是,还有另外三个固定的包和该参数进行拼接,分别是org.apache.struts2.static、template、和org.apache.struts2.interceptor.debugging,中间用空格隔开,经过解析将包名变成路径后存储到一个名叫pathPrefixes的数组中,这些目录中的文件会被自动搜寻。 代码清单9:FilterDispatcher.init()方法 public void init(FilterConfig filterConfig) throws ServletException {
19、 this.filterConfig = filterConfig; dispatcher = createDispatcher(filterConfig); dispatcher.init(); String param = filterConfig.getInitParameter("packages"); String packages = "org.apache.struts2.static template org.apache.struts2.interceptor.deb
20、ugging";
if (param != null) {
packages = param + " " + packages;
}
this.pathPrefixes = parse(packages);
}
代码清单10:FilterDispatcher.createDispatcher()方法
protected Dispatcher createDispatcher(FilterConfig filterConfig) {
Map
21、ms = new HashMap
22、 return new Dispatcher(filterConfig.getServletContext(), params); } 当用户向Struts2发送请求时,FilterDispatcher的doFilter()方法自动调用,这个方法非常关键。首先,Struts2对请求对象进行重新包装,此次包装根据请求内容的类型不同,返回不同的对象,如果为multipart/form-data类型,则返回MultiPartRequestWrapper类型的对象,该对象服务于文件上传,否则返回StrutsRequestWrapper类型的对象,MultiPartReq
23、uestWrapper是StrutsRequestWrapper的子类,而这两个类都是HttpServletRequest接口的实现。包装请求对象如代码清单11所示: 代码清单11:FilterDispatcher.prepareDispatcherAndWrapRequest()方法 protected HttpServletRequest prepareDispatcherAndWrapRequest( HttpServletRequest request, HttpServletResponse response) throws Servl
24、etException { Dispatcher du = Dispatcher.getInstance(); if (du == null) { Dispatcher.setInstance(dispatcher); dispatcher.prepare(request, response); } else { dispatcher = du; } try { re
25、quest = dispatcher.wrapRequest(request, getServletContext()); } catch (IOException e) { String message = "Could not wrap servlet request with MultipartRequestWrapper!"; LOG.error(message, e); throw new ServletException(message, e); }
26、return request; } request对象重新包装后,通过ActionMapper的getMapping()方法得到请求的Action,Action的配置信息存储在ActionMapping对象中,该语句如下:mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());。下面是ActionMapping接口的实现类DefaultActionMapper的getMapping()方法的源代码: 代码清单12:DefaultActionMapper.getMa
27、pping()方法 public ActionMapping getMapping(HttpServletRequest request, ConfigurationManager configManager) { ActionMapping mapping = new ActionMapping(); String uri = getUri(request);//得到请求路径的URI,如:testAtcion.action或testAction!method uri = dropExtension
28、uri);//删除扩展名,默认扩展名为action,在代码中的定义是List extensions = new ArrayList() {{ add("action");}}; if (uri == null) { return null; } parseNameAndNamespace(uri, mapping, configManager);//从uri变量中解析出Action的name和namespace handleSpecialParameters(request, map
29、ping);//将请求参数中的重复项去掉 //如果Action的name没有解析出来,直接返回 if (mapping.getName() == null) { return null; } //下面处理形如testAction!method格式的请求路径 if (allowDynamicMethodCalls) { // handle "name!method" convention. String nam
30、e = mapping.getName(); int exclamation = name.lastIndexOf("!");//!是Action名称和方法名的分隔符 if (exclamation != -1) { mapping.setName(name.substring(0, exclamation));//提取左边为name mapping.setMethod(name.substring(exclamation + 1));//提取右边的method
31、 } } return mapping; } 该代码的活动图如下: (图16) 从代码中看出,getMapping()方法返回ActionMapping类型的对象,该对象包含三个参数:Action的name、namespace和要调用的方法method。 如果getMapping()方法返回ActionMapping对象为null,则FilterDispatcher认为用户请求不是Action,自然另当别论,FilterDispatcher会做一件非常有意思的事:
32、如果请求以/struts开头,会自动查找在web.xml文件中配置的packages初始化参数,就像下面这样(注意粗斜体部分):
代码清单13:web.xml(部分)
33、ages
34、ruts/aaa.txt时会有如图17的输出: (图17) 查找静态资源的源代码如清单14: 代码清单14:FilterDispatcher.findStaticResource()方法 protected void findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException { if (!name.endsWith(".class")) {//忽略class文件 //遍
35、历packages参数 for (String pathPrefix : pathPrefixes) { InputStream is = findInputStream(name, pathPrefix);//读取请求文件流 if (is != null) { ……(省略部分代码) // set the content-type header String contentTy
36、pe = getContentType(name);//读取内容类型 if (contentType != null) { response.setContentType(contentType);//重新设置内容类型 } ……(省略部分代码) try { //将读取到的文件流以每次复制4096个字节的方式循环输出
37、 copy(is, response.getOutputStream()); } finally { is.close(); } return; } } } } 如果用户请求的资源不是以/struts开头——可能是.jsp文件,也可能是.html文件,则通过过滤器链继续往下传送,直到到达请求的资
38、源为止。 如果getMapping()方法返回有效的ActionMapping对象,则被认为正在请求某个Action,将调用Dispatcher.serviceAction(request, response, servletContext, mapping)方法,该方法是处理Action的关键所在。上述过程的源代码如清单15所示。 代码清单15:FilterDispatcher.doFilter()方法 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chai
39、n) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ServletContext servletContext = getServletContext(); String timerKey = "FilterDispatcher_doFilter: ";
40、 try { UtilTimerStack.push(timerKey); request = prepareDispatcherAndWrapRequest(request, response);//重新包装request ActionMapping mapping; try { mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());//得到存储A
41、ction信息的ActionMapping对象 } catch (Exception ex) { ……(省略部分代码) return; } if (mapping == null) {//如果mapping为null,则认为不是请求Action资源 String resourcePath = RequestUtils.getServletPath(request); if
42、 ("".equals(resourcePath) && null != request.getPathInfo()) { resourcePath = request.getPathInfo(); } //如果请求的资源以/struts开头,则当作静态资源处理 if (serveStatic && resourcePath.startsWith("/struts")) { String name = resour
43、cePath.substring("/struts".length()); findStaticResource(name, request, response); } else { //否则,过滤器链继续往下传递 chain.doFilter(request, response); } // The framework did its job here
44、 return; } //如果请求的资源是Action,则调用serviceAction方法。 dispatcher.serviceAction(request, response, servletContext, mapping); } finally { try { ActionContextCleanUp.cleanUp(req); } finally {
45、 UtilTimerStack.pop(timerKey); } } } 这段代码的活动图如图18所示: (图18) 在Dispatcher.serviceAction()方法中,先加载Struts2的配置文件,如果没有人为配置,则默认加载struts-default.xml、struts-plugin.xml和struts.xml,并且将配置信息保存在形如com.opensymphony.xwork2.config.entities.XxxxConfig的类中。 类com.op
46、ensymphony.xwork2.config.providers.XmlConfigurationProvider负责配置文件的读取和解析, addAction()方法负责读取
47、StackConfig对象;loadInterceptorStacks()方法负责将
48、ion { PackageConfig newPackage = buildPackageContext(packageElement); if (newPackage.isNeedsRefresh()) { return newPackage; } if (LOG.isDebugEnabled()) { LOG.debug("Loaded " + newPackage); } // add result types (and defa
49、ult result) to this package addResultTypes(newPackage, packageElement); // load the interceptors and interceptor stacks for this package loadInterceptors(newPackage, packageElement); // load the default interceptor reference for this package loadDefaultInterceptorRef(newPackage, packageElement); // load the default class ref for this package loadDefaultClassRef(newPackage, packageElement); // load the global result list for this package loadGlobalResults(newP
©2010-2025 宁波自信网络信息技术有限公司 版权所有
客服电话:4009-655-100 投诉/维权电话:18658249818