在完成Struts2的HelloWorld后,对Struts2的工作原理进行学习。Struts2框架可以按照模块来划分为Servlet Filters,Struts核心模块,拦截器和用户实现部分,其中需要用户实现的部分只有三个,那就是struts.xml,Action,Template(JSP),如下图:

2.3.31中的org.apache.struts2.dispatcher.ActionContextCleanUp已经被标记为@Deprecated Since Struts 2.1.3,2.1.3之后FilterDispatcher已经改为org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter,2.5.0之后又被移到了父包中,即不在ng包下面,直接在父包中org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter

(1) 在struts2.3.31中FilterDispatcher就是StrutsPrepareAndExecuteFilter,Struts的过滤器根据<url-pattern>/*</url-pattern>拦截请求,doFilter(org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter)核心代码如下:

 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
// 如果常量struts.action.excludePattern指定了不被拦截的Url这里直接放行
chain.doFilter(request, response);
} else {
prepare.setEncodingAndLocale(request, response);
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
request = prepare.wrapRequest(request);
// 通过ActionMapper获取ActionMapping
ActionMapping mapping = prepare.findActionMapping(request, response, true);
if (mapping == null) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
// 调用dispatcher.serviceAction()执行Action
execute.executeAction(request, response, mapping);
}
}
} finally {
prepare.cleanupRequest(request);
}
}

(2)StrutsPrepareAndExecuteFilter通过Dispatcher(org.apache.struts2.dispatcher.Dispatcher)的serviceAction()方法获取ActionProxy去执行Action,核心代码如下:

 public void serviceAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)
throws ServletException {
Map<String, Object> extraContext = createContextMap(request, response, mapping);
// 获取值栈OgnlValueStack implements ValueStack
// If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
boolean nullStack = stack == null;
if (nullStack) {
ActionContext ctx = ActionContext.getContext();
if (ctx != null) {
stack = ctx.getValueStack();
}
}
if (stack != null) {
extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
} String timerKey = "Handling request from Dispatcher";
try {
UtilTimerStack.push(timerKey);
String namespace = mapping.getNamespace();
String name = mapping.getName();
String method = mapping.getMethod();
// 获取Action代理执行Action
ActionProxy proxy = getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, extraContext, true, false); request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); // if the ActionMapping says to go straight to a result, do it!
if (mapping.getResult() != null) {
Result result = mapping.getResult();
result.execute(proxy.getInvocation());
} else {
// Action代理执行Action
proxy.execute();
} // If there was a previous value stack then set it back onto the request
if (!nullStack) {
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
}
} catch (ConfigurationException e) {
logConfigurationException(request, e);
sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e);
} catch (Exception e) {
if (handleException || devMode) {
sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} else {
throw new ServletException(e);
}
} finally {
UtilTimerStack.pop(timerKey);
}
}

(3)Dispatcher通过ActionProxy的execute()方法执行Action,ActionProxy默认的实现是com.opensymphony.xwork2.DefaultActionProxy,ActionProxy执行ActionInvocation.invoke()代理执行Action,核心代码如下:

 public String execute() throws Exception {
ActionContext nestedContext = ActionContext.getContext();
ActionContext.setContext(invocation.getInvocationContext()); String retCode = null; String profileKey = "execute: ";
try {
UtilTimerStack.push(profileKey);
// invoke代理执行Action
retCode = invocation.invoke();
} finally {
if (cleanupContext) {
ActionContext.setContext(nestedContext);
}
UtilTimerStack.pop(profileKey);
}
return retCode;
}

(4)ActionInvocation会执行一系列的Struts的拦截器如上图,而拦截器就只有一个参数,那就是ActionInvocation,在拦截器里面加入一些其他逻辑然后又调用ActionInvocation.invoke()又回到ActionInvocation.invoke(),这样循环直到interceptors.hasNext()没有拦截器为止才执行Action,即调用invokeActionOnly()执行Action,Action执行之后会接着执行executeResult(),上图的Result在Action执行之后,并将executed标记为true,这样result就生成了,当执行拦截器调用ActionInvocation.invoke()之后的代码完成就不会再对result造成任何影响了,核心代码如下:

 public String invoke() throws Exception {
String profileKey = "invoke: ";
try {
UtilTimerStack.push(profileKey); if (executed) {
throw new IllegalStateException("Action has already executed");
} if (interceptors.hasNext()) {
final InterceptorMapping interceptor = interceptors.next();
String interceptorMsg = "interceptor: " + interceptor.getName();
UtilTimerStack.push(interceptorMsg);
try {
// 执行拦截器,拦截器中执行invocation.invoke()回到这里调用下一个拦截器
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
// 所有拦截的执行invocation.invoke()之后的代码完成,此时下面的executed已经被标记成true不会再次执行
}
finally {
UtilTimerStack.pop(interceptorMsg);
}
} else {
// 所有拦截器invocation.invoke()之前的代码执行完后执行Action
resultCode = invokeActionOnly();
} // this is needed because the result will be executed, then control will return to the Interceptor, which will
// return above and flow through again
if (!executed) {
if (preResultListeners != null) {
LOG.trace("Executing PreResultListeners for result [#0]", result); for (Object preResultListener : preResultListeners) {
PreResultListener listener = (PreResultListener) preResultListener; String _profileKey = "preResultListener: ";
try {
UtilTimerStack.push(_profileKey);
listener.beforeResult(this, resultCode);
}
finally {
UtilTimerStack.pop(_profileKey);
}
}
}
// Action执行完成,执行Result
// now execute the result, if we're supposed to
if (proxy.getExecuteResult()) {
executeResult();
}
// 并标记executed为true
executed = true;
}
// 返回ResultCode
return resultCode;
}
finally {
UtilTimerStack.pop(profileKey);
}
}

下面是Struts2配置的默认拦截器:

至此,Struts2一次请求就完成了。

未完,待续。

菜鸟学Struts2——Struts工作原理的更多相关文章

  1. 菜鸟学Struts2——Actions

    在对Struts2的工作原理学习之后,对Struts2的Action进行学习.主要对Struts2文档Guides中的Action分支进行学习,如下图: 1.Model Driven(模型驱动) St ...

  2. Struts2的工作原理及工作流程

    众所周知,Struts2是个非常优秀的开源框架,我们能用Struts2框架进行开发,同时能 快速搭建好一个Struts2框架,但我们是否能把Struts2框架的工作原理用语言表达清楚,你表达的原理不需 ...

  3. Struts2的工作原理(图解)详解

    Struts2的工作原理 上图来源于Struts2官方站点,是Struts 2 的整体结构. 一个请求在Struts2框架中的处理大概分为以下几个步骤(可查看源码:https://github.com ...

  4. Struts2 的工作原理

    Struts2 的工作原理: 1)client向server发出一个http请求.webserver对请求进行解析,假设在StrutsPrepareAndExecuteFilter的请求映射路径(在w ...

  5. [JavaEE,MVC] Struts工作原理

    基本概念 Struts是Apache 基金会Jakarta 项目组的一个Open Source 项目,它采用MVC模式,能够很好地帮助java 开发者利用J2EE开发Web应用.和其他的java架构一 ...

  6. struts2的工作原理

    在学习struts2就必须的了解一下它的工作原理: 首先来看一下这张图 这张工作原理图是官方提供的: 一个请求在Struts2框架中的处理大概分为以下几个步骤 1.客户端初始化一个指向Servlet容 ...

  7. 第一篇——Struts2的工作原理及HelloWorld简单实现

    Struts2工作原理: 一个请求在Struts框架中的处理步骤: 1.客户端初始化一个指向Servlet容器(例如Tomcat)的请求: 2.这个请求经过一系列的过滤器(Filter): 3.接着F ...

  8. struts工作原理(图解)

    Struts2框架的工作原理: 1.服务器启动,会加载我们的xml配置文件中的内容. 2.服务器启动之后,过来一个servlet请求,如user类中的save方法.请求过来先过过滤器(strutsPr ...

  9. Struts2学习一----------Struts2的工作原理及HelloWorld简单实现

    © 版权声明:本文为博主原创文章,转载请注明出处 Struts2工作原理 一个请求在Struts2框架中的处理步骤: 1.客户端初始化一个指向Servlet容器(例如Tomcat)的请求 2.这个请求 ...

随机推荐

  1. 谈谈一些有趣的CSS题目(三)-- 层叠顺序与堆栈上下文知多少

    开本系列,讨论一些有趣的 CSS 题目,抛开实用性而言,一些题目为了拓宽一下解决问题的思路,此外,涉及一些容易忽视的 CSS 细节. 解题不考虑兼容性,题目天马行空,想到什么说什么,如果解题中有你感觉 ...

  2. 创建APPID&&部署服务端教程

    创建APPID&&部署服务端 一.创建APPID 1.打开https://console.developers.google.com ,左击顶部Project,然后左击创建项目 2.输 ...

  3. Chrome V8引擎系列随笔 (1):Math.Random()函数概览

    先让大家来看一幅图,这幅图是V8引擎4.7版本和4.9版本Math.Random()函数的值的分布图,我可以这么理解 .从下图中,也许你会认为这是个二维码?其实这幅图告诉我们一个道理,第二张图的点的分 ...

  4. sql的那些事(一)

    一.概述 书写sql是我们程序猿在开发中必不可少的技能,优秀的sql语句,执行起来吊炸天,性能杠杠的.差劲的sql,不仅使查询效率降低,维护起来也十分不便.一切都是为了性能,一切都是为了业务,你觉得你 ...

  5. autocomplete的使用

    autocomplete使用分为本地调用方法和读取远程读取数据源的方法 (1)本地调用方法 <script src="Scripts/jquery-1.4.1.min.js" ...

  6. TemplateMethod(模块方法模式)

    /** * 模块模式 * @author TMAC-J * 将一个完整的算法分离,分成不同的模块 * 用于有很多步骤的时候,可能以后这些步骤还会增加,把这些步骤分离 * 将有共性的部分放在抽象类中 * ...

  7. CocoaPods的安装、使用、以及遇到的问题

    CocoaPods是什么? 当你开发iOS应用时,会经常使用到很多第三方开源类库,比如JSONKit,AFNetWorking等等.可能某个类库又用到其他类库,所以要使用它,必须得另外下载其他类库,而 ...

  8. Android中Fragment的两种创建方式

    fragment是Activity中用户界面的一个行为或者是一部分.你可以在一个单独的Activity上把多个Fragment组合成为一个多区域的UI,并且可以在多个Activity中再使用.你可以认 ...

  9. 设计模式之工厂模式VS抽象工厂

    一.工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程屏蔽隔离起来,达到提高灵活性的目的. 工厂模式在<Java与模式>中分为三类:1)简单工厂模式(Simple Factor ...

  10. DevExpress第三方控件使用实例之ASPxPopupControl弹出子窗体

    弹出页面控件:ASPxPopupControl, <dxpc:ASPxPopupControl ID="popubCtr" runat="server" ...