Dispatcher已经在之前讲过,这就好办了。FilterDispatcher是Struts2的核心控制器,首先看一下init()方法。

public void init(FilterConfig filterConfig) throws ServletException {     try {     this.filterConfig = filterConfig;     initLogging();     //创建dispatcher,前面都已经讲过啰     dispatcher = createDispatcher(filterConfig);     dispatcher.init();     //注入将FilterDispatcher中的变量通过container注入,如下面的staticResourceLoader     dispatcher.getContainer().inject(this);     //StaticContentLoader在BeanSelectionProvider中已经被注入了依赖关系:DefaultStaticContentLoader     //可以在struts-default.xml中的<bean>可以找到     staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig));     } finally {     ActionContext.setContext(null);     }
}   //下面来看DefaultStaticContentLoader的setHostConfig     public void setHostConfig(HostConfig filterConfig) {     //读取初始参数pakages,调用parse(),解析成类似/org/apache/struts2/static,/template的数组        String param = filterConfig.getInitParameter("packages");     //"org.apache.struts2.static template org.apache.struts2.interceptor.debugging static"     String packages = getAdditionalPackages();     if (param != null) {     packages = param + " " + packages;     }     this.pathPrefixes = parse(packages);     initLogging(filterConfig);     }       

现在回去doFilter的方法,每当有一个Request,都会调用这些Filters的doFilter方法

public void 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     //先看看ValueStackFactory所注入的实现类OgnlValueStackFactory     //new OgnlValueStack     ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();     ActionContext ctx = new ActionContext(stack.getContext());     ActionContext.setContext(ctx);     UtilTimerStack.push(timerKey);     //如果是multipart/form-data就用MultiPartRequestWrapper进行包装
//MultiPartRequestWrapper是StrutsRequestWrapper的子类,两者都是HttpServletRequest实现
//此时在MultiPartRequestWrapper中就会把Files给解析出来,用于文件上传
//所有request都会StrutsRequestWrapper进行包装,StrutsRequestWrapper是可以访问ValueStack
//下面是参见Dispatcher的wrapRequest     // String content_type = request.getContentType();     //if(content_type!= null&&content_type.indexOf("multipart/form-data")!=-1){     //MultiPartRequest multi =getContainer().getInstance(MultiPartRequest.class);     //request =new MultiPartRequestWrapper(multi,request,getSaveDir(servletContext));     //} else {     //     request = new StrutsRequestWrapper(request);     // }     request = prepareDispatcherAndWrapRequest(request, response);     ActionMapping mapping;     try {     //根据url取得对应的Action的配置信息     //看一下注入的DefaultActionMapper的getMapping()方法.Action的配置信息存储在 ActionMapping对象中     mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());     } catch (Exception ex) {     log.error("error getting ActionMapping", ex);     dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);     return;     }     //如果找不到对应的action配置,则直接返回。比如你输入***.jsp等等                                      //这儿有个例外,就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中,当然.class文件除外。如果再没有则跳转到404       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 (staticResourceLoader.canHandle(resourcePath)) {     // 在DefaultStaticContentLoader中:return serveStatic && (resourcePath.startsWith("/struts") || resourcePath.startsWith("/static"));     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的方法     dispatcher.serviceAction(request, response, servletContext, mapping);     } finally {     try {     ActionContextCleanUp.cleanUp(req);     } finally {     UtilTimerStack.pop(timerKey);     }     }
}   
//下面是ActionMapper接口的实现类 DefaultActionMapper的getMapping()方法的源代码:     public ActionMapping getMapping(HttpServletRequest request,     ConfigurationManager configManager) {     ActionMapping mapping = new ActionMapping();     String uri = getUri(request);//得到请求路径的URI,如:testAtcion.action或testAction.do     int indexOfSemicolon = uri.indexOf(";");//修正url的带;jsessionid 时找不到而且的bug     uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;     uri = dropExtension(uri, mapping);//删除扩展名,默认扩展名为action     if (uri == null) {     return null;     }     parseNameAndNamespace(uri, mapping, configManager);//匹配Action的name和namespace     handleSpecialParameters(request, mapping);//去掉重复参数     //如果Action的name没有解析出来,直接返回     if (mapping.getName() == null) {     returnnull;     }     //下面处理形如testAction!method格式的请求路径     if (allowDynamicMethodCalls) {     // handle "name!method" convention.     String name = mapping.getName();     int exclamation = name.lastIndexOf("!");//!是Action名称和方法名的分隔符     if (exclamation != -1) {     mapping.setName(name.substring(0, exclamation));//提取左边为name     mapping.setMethod(name.substring(exclamation + 1));//提取右边的method     }     }     return mapping;     }   

从代码中看出,getMapping()方法返回ActionMapping类型的对象,该对象包含三个参数:Action的name、namespace和要调用的方法method。
  如果getMapping()方法返回ActionMapping对象为null,则FilterDispatcher认为用户请求不是Action,自然另当别论,FilterDispatcher会做一件非常有意思的事:如果请求以/struts开头,会自动查找在web.xml文件中配置的 packages初始化参数,就像下面这样:

<filter>    <filter-name>struts2</filter-name>    <filter-class>    org.apache.struts2.dispatcher.FilterDispatcher     </filter-class>    <init-param>    <param-name>packages</param-name>    <param-value>com.lizanhong.action</param-value>    </init-param>    </filter> 

FilterDispatcher会将com.lizanhong.action包下的文件当作静态资源处理,即直接在页面上显示文件内容,不过会忽略扩展名为class的文件。比如在com.lizanhong.action包下有一个aaa.txt的文本文件,其内容为“中华人民共和国”,访问  http://localhost:8081/Struts2Demo/struts/aaa.txt 时会输出txt中的内容
   FilterDispatcher.findStaticResource()方法

protected void findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {     if (!name.endsWith(".class")) {//忽略class文件     //遍历packages参数     for (String pathPrefix : pathPrefixes) {     InputStream is = findInputStream(name, pathPrefix);//读取请求文件流     if (is != null) {     ...     // set the content-type header     String contentType = getContentType(name);//读取内容类型     if (contentType != null) {     response.setContentType(contentType);//重新设置内容类型     }     ...     try {     //将读取到的文件流以每次复制4096个字节的方式循环输出     copy(is, response.getOutputStream());     } finally {     is.close();     }     return;     }     }     }     }    

如果用户请求的资源不是以/struts开头——可能是.jsp文件,也可能是.html文件,则通过过滤器链继续往下传送,直到到达请求的资源为止。
如果getMapping()方法返回有效的ActionMapping对象,则被认为正在请求某个Action,将调用 Dispatcher.serviceAction(request, response, servletContext, mapping)方法,该方法是处理Action的关键所在。
下面就来看serviceAction,这又回到全局变量dispatcher中了

//Load Action class for mapping and invoke the appropriate Action method, or go directly to the Result.
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,     ActionMapping mapping) throws ServletException {     //createContextMap方法主要把Application、Session、Request的key value值拷贝到Map中     Map<String, Object> extraContext = createContextMap(request, response, mapping, context);     // 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();     Configuration config = configurationManager.getConfiguration();     //创建一个Action的代理对象,ActionProxyFactory是创建ActionProxy的工厂     //参考实现类:DefaultActionProxy和DefaultActionProxyFactory     ActionProxy proxy = config.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!     //如果是Result,则直接转向,关于Result,ActionProxy,ActionInvocation下一讲中再分析     if (mapping.getResult() != null) {     Result result = mapping.getResult();     result.execute(proxy.getInvocation());     } else {     //执行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) {     // WW-2874 Only log error if in devMode     if(devMode) {     LOG.error("Could not find action or result", e);     }     else {     LOG.warn("Could not find action or result", e);     }     sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);     } catch (Exception e) {     sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);     } finally {     UtilTimerStack.pop(timerKey);     }     }    

Struts2源码阅读(五)_FilterDispatcher核心控制器相关推荐

  1. mybatis源码阅读(五) ---执行器Executor

    转载自  mybatis源码阅读(五) ---执行器Executor 1. Executor接口设计与类结构图 public interface Executor {ResultHandler NO_ ...

  2. struts2源码阅读

    Struts2的工作机制分析及实例 一.概述 本章讲述Struts2的工作原理. 读者如果曾经学习过Struts1.x或者有过Struts1.x的开发经验,那么千万不要想当然地以为这一章可以跳过.实际 ...

  3. Spark源码阅读(五) --- Spark的支持的join方式以及join策略

    版本变动 2021-08-30 增加了对Broadcast Hash Join小表大小的评估内容 增加了对Sort Merge Join优于Shuffle Hash Join调用的解释 目录 Spar ...

  4. Struts2源码阅读(四)_DispatcherConfigurationProvider续

    接下来第三步:init_LegacyStrutsProperties() 调用的是调用的是LegacyPropertiesConfigurationProvider 通过比较前面DefaultProp ...

  5. Struts2源码阅读(六)_ActionProxyActionInvocation

    下面开始讲一下主菜ActionProxy了.在这之前最好先去了解一下动态Proxy的基本知识. ActionProxy是Action的一个代理类,也就是说Action的调用是通过ActionProxy ...

  6. Struts2源码阅读(三)_DispatcherConfigurationProvider

    首先强调一下struts2的线程程安全,在Struts2中大量采用ThreadLocal线程局部变量的方法来保证线程的安全,像Dispatcher等都是通过ThreadLocal来保存变量值,使得每个 ...

  7. Struts2源码阅读(一)_Struts2框架流程概述

    1. Struts2架构图 请求首先通过Filter chain,Filter主要包括ActionContextCleanUp,它主要清理当前线程的ActionContext和Dispatcher:F ...

  8. Struts2源码阅读(二)_ActionContext及CleanUP Filter

    1. ActionContext ActionContext是被存放在当前线程中的,获取ActionContext也是从ThreadLocal中获取的.所以在执行拦截器. action和result的 ...

  9. Java struts 2 源码阅读入门

    一 搭建源码阅读环境 首先新建一个struts 2 实例工程,并附着源码: 在Eclipse中新建一个动态web工程:完成后结构如下: 添加如下图的包:可以直接拖到lib文件夹:完成后如下: 新建一个 ...

最新文章

  1. PHP 数组变量之写时复制的要点 只有数组才有的概念。
  2. 时间android版官方版下载,时间块app安卓下载
  3. TL-ER5120路由器配置文档
  4. 什么是 AJAX, what is AJAX(一)
  5. Jmeter4.0分布式测试时启动Jmeter.server时报错
  6. Android 系统(242)---Android init.rc执行顺序
  7. 螺旋矩阵c++语言_一起刷 leetcode 之螺旋矩阵(头条和美团真题)
  8. 为什么Windows7打开项目的方式是灰的不能修改
  9. linux学习 建立静态库,动态库,写简单的makefile
  10. c语言 struct 的初始化
  11. matlab erf erfi,中国樱桃AP2/ERF转录因子在花芽休眠解除过程的表达与作用研究
  12. 采用C语言写文本文件实例
  13. 发布与安装Github Packages
  14. SecureCRT 7.3.4 安装图解----破解图解
  15. AVM 拖动组件 movable-view 介绍
  16. javaWeb 学习笔记14 会话跟踪技术CoolieSession
  17. Android商业模式
  18. 手机mstsc远程工具_如何通过手机远程控制计算机
  19. 光环PgMP学友 | 4A成绩考过,学以致用才是“高分”!
  20. 01: 网络参考模型 、 数据封装与传输 、 数制与数制转换 、 IP地址与子网掩码

热门文章

  1. 论文浅尝 | Global Relation Embedding for Relation Extraction
  2. 笔记:seafile 7.x 安装和部署摘要
  3. RAC(ReactiveCocoa)使用方法(二)
  4. endl与'\n'的区别
  5. 工具推荐-css3渐变生成工具
  6. DATEDIFF 函数使用
  7. flex和js进行参数传递
  8. Spring --getBean用法
  9. leetcode--983.最低票价
  10. Leetcode--字符串压缩