`
lvwenwen
  • 浏览: 932849 次
  • 性别: Icon_minigender_1
  • 来自: 魔都
社区版块
存档分类
最新评论

Struts2核心工作流程与原理

阅读更多

 

这是Struts2官方站点提供的Struts 2 的整体结构。

      

  一个请求在Struts2框架中的处理大概分为以下几个步骤: 
客户端提起一个(HttpServletRequest)请求,如上文在浏览器中输入”http://localhost:8080/TestMvc/add.action”就是提起一个(HttpServletRequest)请求。 
请求被提交到一系列(主要是三层)的过滤器(Filter),如(ActionContextCleanUp、其他过滤器(SiteMesh等)、 FilterDispatcher)。注意这里是有顺序的,先ActionContextCleanUp,再其他过滤器(SiteMesh等)、最后到FilterDispatcher。 
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);  
        }  

FilterDispatcher询问ActionMapper是否需要调用某个Action来处理这个(request)请求,如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交给ActionProxy。 
ActionProxy通过Configuration Manager(struts.xml)询问框架的配置文件,找到需要调用的Action类.
如上文的struts.xml配置

<?xml version="1.0" encoding="GBK"?> 
 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "
http://struts.apache.org/dtds/struts-2.0.dtd"> 
 <struts> 
     <include file="struts-default.xml"/> 
     <package name="struts2" extends="struts-default"> 
         <action name="add"  
             class="edisundong.AddAction" > 
             <result>add.jsp</result> 
         </action>     
     </package> 
 </struts>

如果提交请求的是add.action,那么找到的Action类就是edisundong.AddAction。 
ActionProxy创建一个ActionInvocation的实例,同时ActionInvocation通过代理模式调用Action。但在调用之前ActionInvocation会根据配置加载Action相关的所有Interceptor。(Interceptor是struts2另一个核心级的概念)

下面我们来看看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执行前后运行。
那么什么是拦截器。
拦截器就是AOP(Aspect-Oriented Programming)的一种实现。(AOP是指用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。)
拦截器的例子这里就不展开了。
struts-default.xml文件摘取的内容:

< 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 ="createSession" class ="org.apache.struts2.interceptor.CreateSessionInterceptor" />  
< interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />  
< interceptor name ="external-ref" 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 ="model-driven" class ="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor" />  
< interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor" />  
< interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.ParametersInterceptor" />  
< interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.PrepareInterceptor" />  
< interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor" />  
< interceptor name ="scope" class ="org.apache.struts2.interceptor.ScopeInterceptor" />  
< interceptor name ="servlet-config" 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 ="token-session" class ="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" />  
< interceptor name ="validation" class ="com.opensymphony.xwork2.validator.ValidationInterceptor" />  
< 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" /> 

一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。如上文中将结构返回“add.jsp”,但大部分时候都是返回另外一个action,那么流程又得走一遍………

 

分享到:
评论

相关推荐

    struts2核心工作流程与原理.pdf

    struts2核心工作流程与原理.pdfstruts2核心工作流程与原理.pdfstruts2核心工作流程与原理.pdfstruts2核心工作流程与原理.pdfstruts2核心工作流程与原理.pdf

    struts2核心工作流程与原理.doc

    struts2核心工作流程与原理.doc

    专题资料(2021-2022年)struts2核心工作流程与原理.doc

    专题资料

    Struts2基本原理

    Struts 2框架本身大致可以分为3个部分:核心控制器FilterDispatcher、业务控制器Action和用户实现的企业业务... Struts 2的工作流程相对于Struts 1要简单,与WebWork框架基本相同,所以说Struts 2是WebWork的升级版本。

    struts2流程与流程图

    一个请求在Struts 2框架中的处理大概分为以下几个步骤。...Struts 2的核心控制器是FilterDispatcher,有3个重要的方法:destroy()、doFilter()和Init(),可以在Struts 2的下载文件夹中找到源代码,如代码1所示。

    struts的执行的核心流程时序图

    struts的执行的核心流程时序图

    Struts2 in action中文版

    1.3.3 Struts 2的工作原理 12 1.4 小结 14 第2章 初识Struts 2 16 2.1 声明性架构 16 2.1.1 两种配置 16 2.1.2 声明架构的两种方式 17 2.1.3 智能默认值 20 2.2 简单的HelloWorld示例 20 2.2.1 部署示例应用程序 20...

    Struts2的工作机制分析及实例.doc

    本章讲述Struts2的工作原理 读者如果曾经学习过Struts1.x或者有过Struts1.x的开发经验...虽然Struts2的开发小组极力保留Struts1.x的习惯,但因为Struts2的核心设计完全改变,从思想到设计到工作流程,都有了很大的不同

    struts1流程和原理

    struts1的几个核心组件是值得我们注意的: 1 、ActionServlet(核心控制器)。 2、RequestProcessor类(处理异常的核心组件)。 3、ActionForm(接收页面中传过的数据)。 4、Action(是控制器,主要是从ActionForm中...

    struts控制器核心代码及解释.rar

    struts控制器核心源代码及解释,对希望彻底掌握struts MVC模式工作流程及原理的朋友有帮助。

    SSH框架详解

    个人中的SSH详细介绍,包括struts1的工作原理、Struts1优缺点(为什么要用strust1)、struts1的工作原理及基本配置详解、struts2工作原理、struts2运行机制、Struts2的工作流程、Struts2工作原理、Struts1与Struts2...

    精通Struts基于MVC的Java Web设计与开发 孙卫琴 光盘

    第4章到第7章深入探讨了Struts框架的核心组件ActionServlet和RequestProcessor的实现原理,详细介绍了开发Struts应用的模型、视图和控制器的各种技术,细致的描述了Struts配置文件的每个元素的使用方法。第8章到第9...

    精通 Struts:基于 MVC 的 JavaWeb 设计与开发(PDF)

    第4章到第7章深入探讨了Struts框架的核心组件ActionServlet和RequestProcessor的实现原理,详细介绍了开发Struts应用的模型、视图和控制器的各种技术,细致的描述了Struts配置文件的每个元素的使用方法。第8章到第9...

    Struts原理、开发及项目实施

    Struts原理、开发及项目实施 Holen 2002-9-12 &lt;br/&gt;1、 摘要 2、 关键词 3、 Framework 4、 Struts的起源 5、 Struts工作原理 6、 Struts安装 7、 一个实例 8、 Struts优缺点...

    精通struts:基于mvc的java web设计与开发part2

    第4章到第7章深入探讨了Struts框架的核心组件ActionServlet和 RequestProcessor的实现原理,详细介绍了开发Struts应用的模型、视图和控制器的各种技术,细致的描述了Struts配置文件的每个元素的使用方法。...

    Struts小实例StrutsExample

    关于struts小实例,里附有开发程序的详细解释与对应对Struts核心 ,工程流程原理 ,启动后Struts里流走顺序,是初学者的很好参考实例

    信息办公基于struts的图书管理系统-struts-ts.rar

    通过学习这个系统,你可以深入了解Struts框架的工作原理和使用方法,提高自己的Java Web开发能力。同时,这个项目也可以帮助初学者快速掌握图书管理系统的开发流程和技术要点,为今后的工作和学习打下坚实的基础。...

    精通Struts_基于MVC的Java Web设计与开发

    第4章到第7章深入探讨了Struts框架的核心组件ActionServlet和RequestProcessor的实现原理,详细介绍了开发Struts应用的模型、视图和控制器的各种技术,细致的描述了Struts配置文件的每个元素的使用方法。第8章到第9...

    精通struts:基于mvc的java web设计与开发part3

    第4章到第7章深入探讨了Struts框架的核心组件ActionServlet和 RequestProcessor的实现原理,详细介绍了开发Struts应用的模型、视图和控制器的各种技术,细致的描述了Struts配置文件的每个元素的使用方法。...

Global site tag (gtag.js) - Google Analytics