菜鸟学Struts2——Struts工作原理
在完成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工作原理的更多相关文章
- 菜鸟学Struts2——Actions
在对Struts2的工作原理学习之后,对Struts2的Action进行学习.主要对Struts2文档Guides中的Action分支进行学习,如下图: 1.Model Driven(模型驱动) St ...
- Struts2的工作原理及工作流程
众所周知,Struts2是个非常优秀的开源框架,我们能用Struts2框架进行开发,同时能 快速搭建好一个Struts2框架,但我们是否能把Struts2框架的工作原理用语言表达清楚,你表达的原理不需 ...
- Struts2的工作原理(图解)详解
Struts2的工作原理 上图来源于Struts2官方站点,是Struts 2 的整体结构. 一个请求在Struts2框架中的处理大概分为以下几个步骤(可查看源码:https://github.com ...
- Struts2 的工作原理
Struts2 的工作原理: 1)client向server发出一个http请求.webserver对请求进行解析,假设在StrutsPrepareAndExecuteFilter的请求映射路径(在w ...
- [JavaEE,MVC] Struts工作原理
基本概念 Struts是Apache 基金会Jakarta 项目组的一个Open Source 项目,它采用MVC模式,能够很好地帮助java 开发者利用J2EE开发Web应用.和其他的java架构一 ...
- struts2的工作原理
在学习struts2就必须的了解一下它的工作原理: 首先来看一下这张图 这张工作原理图是官方提供的: 一个请求在Struts2框架中的处理大概分为以下几个步骤 1.客户端初始化一个指向Servlet容 ...
- 第一篇——Struts2的工作原理及HelloWorld简单实现
Struts2工作原理: 一个请求在Struts框架中的处理步骤: 1.客户端初始化一个指向Servlet容器(例如Tomcat)的请求: 2.这个请求经过一系列的过滤器(Filter): 3.接着F ...
- struts工作原理(图解)
Struts2框架的工作原理: 1.服务器启动,会加载我们的xml配置文件中的内容. 2.服务器启动之后,过来一个servlet请求,如user类中的save方法.请求过来先过过滤器(strutsPr ...
- Struts2学习一----------Struts2的工作原理及HelloWorld简单实现
© 版权声明:本文为博主原创文章,转载请注明出处 Struts2工作原理 一个请求在Struts2框架中的处理步骤: 1.客户端初始化一个指向Servlet容器(例如Tomcat)的请求 2.这个请求 ...
随机推荐
- 设计爬虫Hawk背后的故事
本文写于圣诞节北京下午慵懒的午后.本文偏技术向,不过应该大部分人能看懂. 五年之痒 2016年,能记入个人年终总结的事情没几件,其中一个便是开源了Hawk.我花不少时间优化和推广它,得到的评价还算比较 ...
- Atitit 项目语言的选择 java c#.net php??
Atitit 项目语言的选择 java c#.net php?? 1.1. 编程语言与技术,应该使用开放式的目前流行的语言趋势1 1.2. 从个人职业生涯考虑,java优先1 1.3. 从项目实际来 ...
- Android 5.0 到 Android 6.0 + 的深坑之一 之 .so 动态库的适配
(原创:http://www.cnblogs.com/linguanh) 目录: 前序 一,问题描述 二,为何会如此"无情"? 三,目前存在该问题的知名SDK 四,解决方案,1 对 ...
- .Net语言 APP开发平台——Smobiler学习日志:手机应用的TextTabBar快速实现方式
参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-put.html http://www.yuanjiaocheng.net/we ...
- 如何使用swing创建一个BeatBox
首先,我们需要回顾一些内容(2017-01-04 14:32:14): 1.Swing组件 Swing的组件(component,或者称之为元件),是较widget更为正确的术语,它们就是会放在GUI ...
- iOS自定义model排序
在开发过程中,可能需要按照model的某种属性排序. 1.自定义model @interface Person : NSObject @property (nonatomic,copy) NSStri ...
- Mysql - 触发器/视图
触发器在之前的项目中, 应用的着实不多, 没有办法的时候, 才会去用这个. 因为这个东西在后期并不怎么好维护, 也容易造成紊乱. 我最近的项目中, 由于数据库设计(别人设计的)原因, 导致一些最简单功 ...
- Git时间(第一次写,这个怎么玩啊)
1.安装 Liunx直接打开shell界面,输入:sudo apt-get install git-core ,按下回车之后输入密码即可完成安装: Windows系统在https://git-for- ...
- logstash服务启动脚本
logstash服务启动脚本 最近在弄ELK,发现logstash没有sysv类型的服务启动脚本,于是按照网上一个老外提供的模板自己进行修改 #添加用户 useradd logstash -M -s ...
- NodeJs 开发微信公众号(四)微信网页授权
微信的网页授权指的是在微信公众号中访问第三方网页时获取用户地理.个人等信息的权限.对于开发了自己的网页app应用时,获取个人的信息非常重要.上篇博客讲到了注册时可以获取用户的信息,很多人会问为什么还需 ...