struts2的核心和工作原理 (转)
转自--------http://blog.csdn.net/laner0515/article/details/27692673
在学习struts2之前,首先我们要明白使用struts2的目的是什么?它能给我们带来什么样的好处?
设计目标
Struts设计的第一目标就是使MVC模式应用于web程序设计。在这儿MVC模式的好处就不在提了。
技术优势
Struts2有两方面的技术优势,一是所有的Struts2应用程序都是基于client/server HTTP交换协议,The Java Servlet API揭示了Java Servlet只是Java API的一个很小子集,这样我们可以在业务逻辑部分使用功能强大的Java语言进行程序设计。
二是提供了对MVC的一个清晰的实现,这一实现包含了很多参与对所以请求进行处理的关键组件,如:拦截器、OGNL表达式语言、堆栈。
因为struts2有这样目标,并且有这样的优势,所以,这是我们学习struts2的理由,下面,我们在深入剖析一下struts的工作原理。
工作原理
Suruts2的工作原理可以用下面这张图来描述,下面我们分步骤介绍一下每一步的核心内容
一个请求在Struts2框架中的处理大概分为以下几个步骤
1、客户端初始化一个指向Servlet容器(例如Tomcat)的请求
2、这个请求经过一系列的过滤器(Filter)(这些过滤器中有一个叫做ActionContextCleanUp的可选过滤器,这个过滤器对于Struts2和其他框架的集成很有帮助,例如:SiteMesh Plugin)
3、接着FilterDispatcher被调用,FilterDispatcher询问ActionMapper来决定这个请是否需要调用某个Action
FilterDispatcher是控制器的核心,就是mvc中c控制层的核心。下面粗略的分析下我理解的FilterDispatcher工作流程和原理:FilterDispatcher进行初始化并启用核心doFilter
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException ...{
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse) res;
- ServletContext servletContext = filterConfig.getServletContext();
- // 在这里处理了HttpServletRequest和HttpServletResponse。
- DispatcherUtils du = DispatcherUtils.getInstance();
- du.prepare(request, response);//正如这个方法名字一样进行locale、encoding以及特殊request parameters设置
- try ...{
- request = du.wrapRequest(request, servletContext);//对request进行包装
- } catch (IOException e) ...{
- String message = "Could not wrap servlet request with MultipartRequestWrapper!";
- LOG.error(message, e);
- throw new ServletException(message, e);
- }
- ActionMapperIF mapper = ActionMapperFactory.getMapper();//得到action的mapper
- ActionMapping mapping = mapper.getMapping(request);// 得到action 的 mapping
- 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();
- }
- if ("true".equals(Configuration.get(WebWorkConstants.WEBWORK_SERVE_STATIC_CONTENT))
- && resourcePath.startsWith("/webwork")) ...{
- String name = resourcePath.substring("/webwork".length());
- findStaticResource(name, response);
- } else ...{
- // this is a normal request, let it pass through
- chain.doFilter(request, response);
- }
- // WW did its job here
- return;
- }
- Object o = null;
- try ...{
- //setupContainer(request);
- o = beforeActionInvocation(request, servletContext);
- //整个框架最最核心的方法,下面分析
- du.serviceAction(request, response, servletContext, mapping);
- } finally ...{
- afterActionInvocation(request, servletContext, o);
- ActionContext.setContext(null);
- }
- }
- du.serviceAction(request, response, servletContext, mapping);
- //这个方法询问ActionMapper是否需要调用某个Action来处理这个(request)请求,如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交给ActionProxy
- public void serviceAction(HttpServletRequest request, HttpServletResponse response, String namespace, String actionName, Map requestMap, Map parameterMap, Map sessionMap, Map applicationMap) ...{
- HashMap extraContext = createContextMap(requestMap, parameterMap, sessionMap, applicationMap, request, response, getServletConfig()); //实例化Map请求 ,询问ActionMapper是否需要调用某个Action来处理这个(request)请求
- extraContext.put(SERVLET_DISPATCHER, this);
- OgnlValueStack stack = (OgnlValueStack) request.getAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY);
- if (stack != null) ...{
- extraContext.put(ActionContext.VALUE_STACK,new OgnlValueStack(stack));
- }
- try ...{
- ActionProxy proxy = ActionProxyFactory.getFactory().createActionProxy(namespace, actionName, extraContext);
- //这里actionName是通过两道getActionName解析出来的, FilterDispatcher把请求的处理交给ActionProxy,下面是ServletDispatcher的 TODO:
- request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY, proxy.getInvocation().getStack());
- proxy.execute();
- //通过代理模式执行ActionProxy
- if (stack != null)...{
- request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY,stack);
- }
- } catch (ConfigurationException e) ...{
- log.error("Could not find action", e);
- sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e);
- } catch (Exception e) ...{
- log.error("Could not execute action", e);
- sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
- }
- }
4、如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交给ActionProxy
5、ActionProxy通过ConfigurationManager询问框架的配置文件,找到需要调用的Action类 ,这里,我们一般是从struts.xml配置中读取。
6、ActionProxy创建一个ActionInvocation的实例。
7、ActionInvocation实例使用命名模式来调用,在调用Action的过程前后,涉及到相关拦截器(Intercepter)的调用。
下面我们来看看ActionInvocation是如何工作的:
ActionInvocation是Xworks 中Action 调度的核心。而对Interceptor 的调度,也正是由ActionInvocation负责。ActionInvocation 是一个接口,而DefaultActionInvocation 则是Webwork 对ActionInvocation的默认实现。
Interceptor的调度流程大致如下:
1.ActionInvocation初始化时,根据配置,加载Action相关的所有Interceptor。
2. 通过ActionInvocation.invoke方法调用Action实现时,执行Interceptor。
Interceptor将很多功能从我们的Action中独立出来,大量减少了我们Action的代码,独立出来的行为具有很好的重用性。XWork、WebWork的许多功能都是有Interceptor实现,可以在配置文件中组装Action用到的Interceptor,它会按照你指定的顺序,在Action执行前后运行。
这里,我们简单的介绍一下Interceptor
在struts2中自带了很多拦截器,在struts2-core-2.1.6.jar这个包下的struts-default.xml中我们可以发现:
- <interceptors>
- <interceptor name="alias"class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
- <interceptor name="autowiring"class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
- <interceptor name="chain"class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/>
- <interceptor name="conversionError"class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>
- <interceptor name="clearSession"class="org.apache.struts2.interceptor.ClearSessionInterceptor"/>
- <interceptor name="createSession"class="org.apache.struts2.interceptor.CreateSessionInterceptor"/>
- <interceptor name="debugging"class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor"/>
- <interceptor name="externalRef"class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor"/>
- <interceptor name="execAndWait"class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/>
- <interceptor name="exception"class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>
- <interceptor name="fileUpload"class="org.apache.struts2.interceptor.FileUploadInterceptor"/>
- <interceptor name="i18n"class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>
- <interceptor name="logger"class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/>
- <interceptor name="modelDriven"class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
- <interceptor name="scopedModelDriven"class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/>
- <interceptor name="params"class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>
- <interceptor name="actionMappingParams"class="org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/>
- <interceptor name="prepare"class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/>
- <interceptor name="staticParams"class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>
- <interceptor name="scope"class="org.apache.struts2.interceptor.ScopeInterceptor"/>
- <interceptor name="servletConfig"class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
- <interceptor name="sessionAutowiring"class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/>
- <interceptor name="timer"class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>
- <interceptor name="token"class="org.apache.struts2.interceptor.TokenInterceptor"/>
- <interceptor name="tokenSession"class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>
- <interceptor name="validation"class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>
- <interceptor name="workflow"class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/>
- <interceptor name="store"class="org.apache.struts2.interceptor.MessageStoreInterceptor"/>
- <interceptor name="checkbox"class="org.apache.struts2.interceptor.CheckboxInterceptor"/>
- <interceptor name="profiling"class="org.apache.struts2.interceptor.ProfilingActivationInterceptor"/>
- <interceptor name="roles"class="org.apache.struts2.interceptor.RolesInterceptor"/>
- <interceptor name="jsonValidation"class="org.apache.struts2.interceptor.validation.JSONValidationInterceptor"/>
- <interceptornameinterceptorname="annotationWorkflow"class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>
对于sturts2自带的拦截器,使用起来就相对比较方便了,我们只需要在struts.xml的action标签中加入<interceptor-ref name=" logger " />并且struts.xml扩展struts-default,就可以使用,
如果是要自定义拦截器,首先需要写一个拦截器的类:
- package ceshi;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
- publicclassAuthorizationInterceptor extends AbstractInterceptor {
- @Override
- public Stringintercept(ActionInvocation ai)throws Exception {
- System.out.println("abc");
- return ai.invoke();
- }
- }
并且在struts.xml中进行配置
- <!DOCTYPEstruts PUBLIC
- "-//Apache SoftwareFoundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="test"extends="struts-default">
- <interceptors>
- <interceptor name="abc"class ="ceshi.AuthorizationInterceptor"/>
- </interceptors>
- <action name="TestLogger"class="vaannila.TestLoggerAction">
- <interceptor-refnameinterceptor-refname="abc"/>
- <result name="success">/success.jsp</result>
- </action>
- </package>
- </struts>
8、一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。返回结果通常是(但不总是,也可能是另外的一个Action链)一个需要被表示的JSP或者FreeMarker的模版。在表示的过程中可以使用Struts2 框架中继承的标签。在这个过程中需要涉及到ActionMapper
在上述过程中所有的对象(Action,Results,Interceptors,等)都是通过ObjectFactory来创建的。
Struts2和struts1的比较
struts2相对于struts1来说简单了很多,并且功能强大了很多,我们可以从几个方面来看:
从体系结构来看:struts2大量使用拦截器来出来请求,从而允许与业务逻辑控制器 与 servlet-api分离,避免了侵入性;而struts1.x在action中明显的侵入了servlet-api.
从线程安全分析:struts2.x是线程安全的,每一个对象产生一个实例,避免了线程安全问题;而struts1.x在action中属于单线程。
性能方面:struts2.x测试可以脱离web容器,而struts1.x依赖servlet-api,测试需要依赖web容器。
请求参数封装对比:struts2.x使用ModelDriven模式,这样我们 直接 封装model对象,无需要继承任何struts2的基类,避免了侵入性。
标签的优势:标签库几乎可以完全替代JSTL的标签库,并且 struts2.x支持强大的ognl表达式。
当然,struts2和struts1相比,在 文件上传,数据校验 等方面也 方便了好多。在这就不详谈了。
一个比较优秀的框架可以帮着我们更高效,稳定的开发合格的产品,不过我们也不要依赖框架,我们只要理解了思想,设计模式,我们可以自己扩展功能,不然 就要 永远让别人牵着走了!
struts2的核心和工作原理 (转)的更多相关文章
- struts2的核心和工作原理
struts2的核心和工作原理 设计目标 Struts设计的第一目标就是使MVC模式应用于web程序设计.技术优势 Struts2有两方面的技术优势,一是所有的Struts2应用程序都是基于clien ...
- struts2的核心和工作原理 <转>
在学习struts2之前,首先我们要明白使用struts2的目的是什么?它能给我们带来什么样的好处? 设计目标 Struts设计的第一目标就是使MVC模式应用于web程序设计.在这儿MVC模式的好处就 ...
- struts2(2.0.x到2.1.2版本)的核心和工作原理(转)
在学习struts2之前,首先我们要明白使用struts2的目的是什么?它能给我们带来什么样的好处? 设计目标 Struts设计的第一目标就是使MVC模式应用于web程序设计.在这儿MVC模式的好处就 ...
- struts2核心和工作原理
转至:http://blog.csdn.net/laner0515/article/details/27692673 在学习struts2之前,首先我们要明白使用struts2的目的是什么?它能给我们 ...
- Struts2(一)入门及工作原理
Apache Struts 2 是一种流行的 Java模型 - 视图 - 控制器(MVC)框架,成功地结合了 WebWork和Struts1.x 两种 web 框架. Apache Struts2与S ...
- structs2的核心和工作原理
在学习struts2之前,首先我们要明白使用struts2的目的是什么?它能给我们带来什么样的好处? 设计目标 Struts设计的第一目标就是使MVC模式应用于web程序设计.在这儿MVC模式的 ...
- Struts2 的核心、执行原理
转自: http://www.cnblogs.com/xiadongqing/p/5240615.html 在学习struts2之前,首先我们要明白使用struts2的目的是什么?它能给我们带来什么样 ...
- strust2的核心和工作原理
在学习strust2之前,我们要明白使用struts2的目的是什么?它能给我们带来什么样的好处? 设计目标 Strust设计的第一目标就是使MVC模式应用于web程序设计. 技术优势 Struts2有 ...
- Struts2 源码分析-----工作原理分析
请求过程 struts2 架构图如下图所示: 依照上图,我们可以看出一个请求在struts的处理大概有如下步骤: 1.客户端初始化一个指向Servlet容器(例如Tomcat)的请求: 2.这个请求经 ...
随机推荐
- 03深入理解C指针之---变量与内存
该系列文章源于<深入理解C指针>的阅读与理解,由于本人的见识和知识的欠缺可能有误,还望大家批评指教. C语言是一种编译型的语言,C源代码在编译成可执行文件后,经常以以下三种方式使用内存: ...
- Vbat 1.8V,接充電器,GPIO_CHG_EN pin 竟然是 high!
Schematic : Precondition : Vbat 1.8V Plugin adapter Preloader doesn't enable GPIO_CHG_EN Origin : 做個 ...
- STL之set的用法
1.关于set 首先,set是关联容器,set作为一个容器是用来存储同一种数据类型的数据结构,基本功能与数组相似.不同的是,在set中每个元素的值都是唯一的.而且系统能够根据元素的值自动进行排序.但是 ...
- docker mysql 导入导出数据
导出数据 1.导出mysql单张表结构和数据: docker exec -it my-mysql mysqldump dbname -uroot -p123456 --tables tname > ...
- html5(拖拽2)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- BZOJ 4568 [Scoi2016]幸运数字(树链剖分 + 异或线性基)
题目链接 BZOJ 4568 考虑树链剖分+线段树维护每一段区域的异或线性基 对于每个询问,求出该点集的异或线性基.然后求一下这个线性基里面能异或出的最大值即可. #include <bits ...
- 济南day3
连续几天都有点炸 预计的分拿不到,调整好心态,考试的时候多想一下,think twice,code once 唉,什么情况啊 题解链接 0+0+0 T1读错题输出反了 n*m%2判断是否==1 T2 ...
- Codeforces 323 B Tournament-graph
Discription In this problem you have to build tournament graph, consisting of n vertices, such, that ...
- Concurrency and Application Design (三)
Operation Queues operation object是 NSOperation class实例用来封装想要执行的任务.nsoperation class是抽象类必须子类化. NSInvo ...
- mac git安装及github配置
准备下载一个react的demo程序包,需要本地用到git.早就向配置了,那就安装配置一下吧. 首先,原来mac已经安装了git,版本 2.7 ,我用 brew又安装了一份git 版本 2.10.2. ...