struts2源码的解读 .

学习开源框架最好的方法,莫过于仔细阅读源代码,这样既可以体会大牛们巧妙的设计,还可以看看大牛们的写代码的风格。对比中找缺陷,它就像一面镜子,会让我看到很多自己的缺点,受益颇多。

以下是自己学习的一些资料,有些事自己网上看的,有的是自己从代码中发现的,学习,如果有不对的地方,希望高手指出,小弟在此谢过

1 struts2的源码简介

Struts2是Struts社区和WebWork社区的共同成果,我们甚至可以说,Struts2是WebWork的升级版,他采用的正是WebWork的核心,特别要指出的是构建在WebWork基础之上的Struts2是一个运行稳定、性能优异、设计成熟的WEB框架。

分析struts2源码,因为Struts2与WebWork的关系如此密不可分,所以下载并认真研究xwork的源码是很有必要的。现在http://struts.apache.org/download.cgi#struts234

Struts2的源代码中包含有xwrok的源码具体包如下图(本人尽量把最新的struts)

其中struts2的核心代码的源文件如下图所以

Struts2中主要的包和类的介绍

Struts2框架的正常运行,除了占核心地位的xwork的支持以外,Struts2本身也提供了许多类,这些类被分门别类组织到不同的包中。从源代码中发现,基本上每一个Struts2类都访问了WebWork提供的功能,从而也可以看出Struts2与WebWork千丝万缕的联系。但无论如何,Struts2的核心功能比如将请求委托给哪个Action处理都是由xwork完成的,Struts2只是在WebWork的基础上做了适当的简化、加强和封装,并少量保留Struts1.x中的习惯。

包名

说明

org.apache.struts2. components

该包封装视图组件,Struts2在视图组件上有了很大加强,不仅增加了组件的属性个数,更新增了几个非常有用的组件,如updownselect、doubleselect、datetimepicker、token、tree等。另外,Struts2可视化视图组件开始支持主题(theme),缺省情况下,使用自带的缺省主题,如果要自定义页面效果,需要将组件的theme属性设置为simple。

org.apache.struts2. config

该包定义与配置相关的接口和类。实际上,工程中的xml和properties文件的读取和解析都是由WebWork完成的,Struts只做了少量的工作。

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

只定义了一个类:DWRValidator。

org.apache.struts2.views

提供freemarker、jsp、velocity等不同类型的页面呈现。

Struts2中一些重要的类说明

类名

说明

org.apache.struts2.dispatcher. Dispatcher

该类有两个作用:初始化、调用指定的Action的execute()方法。

org.apache.struts2.dispatcher. FilterDispatcher

这是一个过滤器。文档中已明确说明,如果没有经验,配置时请将url-pattern的值设成/*。该类有四个作用:执行Action、清理ActionContext,避免内存泄漏、处理静态内容(Serving static content)、为请求启动xwork’s的截拦器链。

com.opensymphony.xwork2. ActionProxy

Action的代理接口。

com.opensymphony.xwork2. ctionProxyFactory

生产ActionProxy的工厂。

com.opensymphony.xwork2.ActionInvocation

负责调用Action和截拦器。

com.opensymphony.xwork2.config.providers. XmlConfigurationProvider

负责Struts2的配置文件的解析。

2 Struts2架构

Struts2的工作流程图如下,此图来自于struts2的官方文档

从图中可以看出,一个请求在struts2框架中分为以下几个步骤:

1) 客户端初始化一个指向servlet容器的请求;

2) 这个请求经过一系列的过滤器(Filter)这些过滤器中有一个叫做ActionContextCleanUp的可选择过滤器,这个过滤器对于struts2和其他框架的集成很有帮助,例如SiteMEsh Plugin等;

3) 接着FilterDispatcher被调用,FilterDispatcher询问ActionMapper来决定这个请求是否需要调用某个Action;

4) 如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交过ActionProxy;

5) ActionProxy通过Configuration Manager询问框架配置文件,找到对应的Action类;

6) ActionProxy创建一个ActionInvocation实例

7) ActionInvocation实例使用命名模式来调用在Action过程前后,涉及到相关的拦截器(intercepter)的调用;

8) 一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。返回结果通常是一个需求蓓表示的jsp或者FreeMarker的模板。在表示的过程中可以使用Struts2框架中继承标签,这个过程中涉及到ActionMapper

请求首先通过Filter chain,Filter主要包括ActionContextCleanUp,它主要清理当前线程的ActionContext和Dispatcher;FilterDispatcher主要通过AcionMapper来决定需要调用哪个Action。ActionMapper取得了ActionMapping后,在Dispatcher的serviceAction方法里创建ActionProxy,ActionProxy创建ActionInvocation,然后ActionInvocation调用Interceptors,执行Action本身,创建Result并返回,当然,如果要在返回之前做些什么,可以实现PreResultListener。

3 Struts2源代码解读

和struts1.x不同,struts2的启动是通过FilterDispatcher过滤器实现的。下面是该过滤器在web.xml中的配置

struts

org.apache.struts2.dispatcher.FilterDispatcher

struts

/*

建议在对struts2不熟悉的情况下,最好将url-pattern配置为/*,这样该过滤器将拦截所有的请求。实际FilterDispatcher类除了实现Filter接口之外,还实现了StrutsStatics接口,继承代码如下: publicclass FilterDispatcher implements StrutsStatics, Filter {}

StrutsStatics并没有定义业务方法,只是定义了若干个常量。Struts2对常用的接口进行了重新封装,比如HttpServletRequest、HttpServletResponse、HttpServletContext等。

容器启动后,FilterDispatcher被实例化,调用init(FilterConfig filterConfig)方法。该方法创建Dispatcher实例,并将FilterDispatcherde配置的初始化参数传到对象中,并负责Action的执行。

publicvoid init(FilterConfig filterConfig) throws ServletException {

try {

this.filterConfig = filterConfig;

initLogging();

dispatcher = createDispatcher(filterConfig);

dispatcher.init();

dispatcher.getContainer().inject(this);

staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig));

} finally {

ActionContext.setContext(null);

}

}

其中dispatcher.init();方法完成了对struts2的基本配置文件的读取,源码如下

dispatcher.init();

publicvoid init() {

if (configurationManager == null) {

configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);

}

try {

init_DefaultProperties(); // [1]完成读取org/apache/struts2/default.properties的配置信息,如果项目中需要覆盖,可以在classpath里的struts.properties里覆写

init_TraditionalXmlConfigurations(); // [2]此方法是对struts-default.xml和struts2.xml文件的加载,介于此文件比较重要,所以在下面列举了本函数的源代码

init_LegacyStrutsProperties(); // [3]

init_CustomConfigurationProviders(); // [5]

init_FilterInitParameters() ; // [6]

init_AliasStandardObjects() ; // [7]

Container container = init_PreloadConfiguration();

container.inject(this);

init_CheckConfigurationReloading(container);

init_CheckWebLogicWorkaround(container);

if (!dispatcherListeners.isEmpty()) {

for (DispatcherListener l : dispatcherListeners) {

l.dispatcherInitialized(this);

}

}

} catch (Exception ex) {

if (LOG.isErrorEnabled())

LOG.error("Dispatcher initialization failed", ex);

thrownew StrutsException(ex);

}

}

//读取Struts2的struts-default.xml和struts.xml

privatevoid init_TraditionalXmlConfigurations() {

//首先读取web.xml中的config初始值

//如果没有配置就使用默认”struts-default.xml,struts-plugin.xml

// struts.xml”文件,这也是为什么默认的配置文件必须取名为这三个文件

//如果不想使用默认的名称,直接在web.xml中配置config初始值即可。

String configPaths = initParams.get("config");

if (configPaths == null) {

configPaths = DEFAULT_CONFIGURATION_PATHS;

}

String[] files = configPaths.split("\\s*[,]\\s*");

//一次解析配置文件,xwork.xml单独解析

for (String file : files) {

if (file.endsWith(".xml")) {

if ("xwork.xml".equals(file)) {

configurationManager.addConfigurationProvider(createXmlConfigurationProvider(file, false));

} else {

configurationManager.addConfigurationProvider(createStrutsXmlConfigurationProvider(file, false, servletContext));

}

} else {

thrownew IllegalArgumentException("Invalid configuration file name");

}

}

}

在上面的configurationManager.addConfigurationProvider(createStrutsXmlConfigurationProvider(file, false, servletContext));执行会创建一个下面的类对象。

publicclass StrutsXmlConfigurationProvider extends XmlConfigurationProvider {}

此类继承XmlConfigurationProvider,而XmlConfigurationProvider又实现了接口ConfigurationProvider 接口。XmlConfigurationProvider负责配置文件的读取和解析,addAction()负责加载Struts2配置文件中的action. addAction()方法负责读取标签,并将数据保存在ActionConfig中;addResultTypes()方法负责将标签转化为ResultTypeConfig对象;loadInterceptors()方法负责将标签转化为InterceptorConfi对象;loadInterceptorStack()方法负责将标签转化为InterceptorStackConfig对象;loadInterceptorStacks()方法负责将标签转化成InterceptorStackConfig对象。而上面的方法最终会被addPackage()方法调用,将所读取到的数据汇集到PackageConfig对象中

当用户想struts2发送请求时,FilterDispatcher的doFilter()方法自动调用,这个方法非常关键。首先,struts2对请求对象进行了重新包装,此次包装根据请求内容的类型不容,返回不同的对象,如果为multipart/form-data类型,则返回StrutsPartRequestWrapper类型的对象,该对象服务于文件上传,否则返回StrutsRequestWrapper类型的对象,前者是后者的子类。代码如下:

publicvoid 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 {

// FIXME: this should be refactored better to not duplicate work with the action invocation

ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();

ActionContext ctx = new ActionContext(stack.getContext());

ActionContext.setContext(ctx);

UtilTimerStack.push(timerKey);

request = prepareDispatcherAndWrapRequest(request, response);//重新包装request

ActionMapping mapping;

try {

mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());//获取Action的值,一个url对应一个action,如果此action为null则认为无action请求,在后面有判断

} catch (Exception ex) {

log.error("error getting ActionMapping", ex);

dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);

return;

}

if (mapping == null) {

// there is no action in this request, should we look for a static resource?

String resourcePath = RequestUtils.getServletPath(request);

if ("".equals(resourcePath) && null != request.getPathInfo()) {

resourcePath = request.getPathInfo();

}

//如果请求资源以/struts开头,则当做静态资源处理

if (staticResourceLoader.canHandle(resourcePath)) {

staticResourceLoader.findStaticResource(resourcePath, request, response);

} else {

// this is a normal request, let it pass through

chain.doFilter(request, response);

}

// The framework did its job here

return;

}

//如果请求资源是action,则调用serviceAction方法

dispatcher.serviceAction(request, response, servletContext, mapping);

} finally {

dispatcher.cleanUpRequest(request);

try {

ActionContextCleanUp.cleanUp(req);

} finally {

UtilTimerStack.pop(timerKey);

}

devModeOverride.remove();

}

}

Dispatcher类最重要的一个方法是publicvoid serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,ActionMapping mapping) throws ServletException{}此方法