【Web容器】Tomcat源码分析(6)-请求原理分析(中)

来源:互联网 发布:阿里云服务器托管 编辑:程序博客网 时间:2024/06/06 09:53

前言

  本文继续讲解TOMCAT的请求原理分析,建议朋友们阅读本文时首先阅读过《Tomcat7.0源码分析——请求原理分析(上)》和《Tomcat7.0源码分析——请求原理分析(中)》。在《Tomcat7.0源码分析——请求原理分析(中)》一文我简单讲到了Pipeline,但并未完全展开,本文将从Pipeline开始讲解请求原理的剩余内容。

管道

  在Tomcat中管道Pipeline是一个接口,定义了使得一组阀门Valve按照顺序执行的规范,Pipeline中定义的接口如下:

  • getBasic:获取管道的基础阀门;
  • setBasic:设置管道的基础阀门;
  • addValve:添加阀门;
  • getValves:获取阀门集合;
  • removeValve:移除阀门;
  • getFirst:获取第一个阀门;
  • isAsyncSupported:当管道中的所有阀门都支持异步时返回ture,否则返回false;
  • getContainer:获取管道相关联的容器,比如StandardEngine;
  • setContainer:设置管道相关联的容器。

  Engine、Host、Context及Wrapper等容器都定义了自身的Pipeline,每个Pipeline都包含一到多个Valve。Valve定义了各个阀门的接口规范,其类继承体系如图1所示。


图1  Valve的类继承体系

这里对图1中的主要部分(LifecycleMBeanBase及Contained接口在《Tomcat7.0源码分析——生命周期管理》一文已详细阐述过)进行介绍:

  • Valve:定义了管道中阀门的接口规范,getNext和setNext分别用于获取或者设置当前阀门的下游阀门,invoke方法用来应用当前阀门的操作。
  • ValveBase:Valve接口的基本实现,ValveBase与Valve的具体实现采用抽象模板模式将管道中的阀门串联起来。
  • StandardEngineValve:StandardEngine中的唯一阀门,主要用于从request中选择其host映射的Host容器StandardHost。
  • AccessLogValve:StandardHost中的第一个阀门,主要用于管道执行结束之后记录日志信息。
  • ErrorReportValve:StandardHost中紧跟AccessLogValve的阀门,主要用于管道执行结束后,从request对象中获取异常信息,并封装到response中以便将问题展现给访问者。
  • StandardHostValve:StandardHost中最后的阀门,主要用于从request中选择其context映射的Context容器StandardContext以及访问request中的Session以更新会话的最后访问时间。
  • StandardContextValve:StandardContext中的唯一阀门,主要作用是禁止任何对WEB-INF或META-INF目录下资源的重定向访问,对应用程序热部署功能的实现,从request中获得StandardWrapper。
  • StandardWrapperValve:StandardWrapper中的唯一阀门,主要作用包括调用StandardWrapper的loadServlet方法生成Servlet实例和调用ApplicationFilterFactory生成Filter链。
  有了以上对Tomcat的管道设计的讲述,我们下面详细剖析其实现。  在《Tomcat7.0源码分析——请求原理分析(中)》一文中讲到执行管道的代码如代码清单1所示。

代码清单1

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. connector.getService().getContainer().getPipeline().getFirst().invoke(request, response);  

代码清单1中的getContainer方法获取到的实际是StandardService中的StandardEngine容器,根据《Tomcat7.0源码分析——生命周期管理》一文的内容,我们知道StandardEngine继承自ContainerBase,所以这里的getPipeline方法实际是ContainerBase实现的,代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public Pipeline getPipeline() {  
  2.   
  3.     return (this.pipeline);  
  4.   
  5. }  

pipeline在ContainerBase实例化时生成,代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. protected Pipeline pipeline =  
  2.     CatalinaFactory.getFactory().createPipeline(this);  

这里的CatalinaFactory采用单例模式实现,要获取CatalinaFactory实例,只能通过调用getFactory方法,见代码清单2。createPipeline方法中创建了StandardPipeline,StandardPipeline是Pipeline的标准实现。

代码清单2

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class CatalinaFactory {  
  2.       
  3.     private static CatalinaFactory factory = new CatalinaFactory();  
  4.       
  5.     public static CatalinaFactory getFactory() {  
  6.         return factory;  
  7.     }  
  8.       
  9.     private CatalinaFactory() {  
  10.         // Hide the default constructor  
  11.     }  
  12.       
  13.     public String getDefaultPipelineClassName() {  
  14.         return StandardPipeline.class.getName();  
  15.     }  
  16.   
  17.     public Pipeline createPipeline(Container container) {  
  18.         Pipeline pipeline = new StandardPipeline();  
  19.         pipeline.setContainer(container);  
  20.         return pipeline;  
  21.     }  
  22. }  

代码清单1随后调用了StandardPipeline的getFirst方法(见代码清单3)用来获取管道中的第一个Valve ,由于Tomcat并没有为StandardEngine的StandardPipeline设置first,因此将返回StandardPipeline的basic。

代码清单3

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public Valve getFirst() {  
  2.     if (first != null) {  
  3.         return first;  
  4.     }  
  5.       
  6.     return basic;  
  7. }  

代码清单3中的basic的类型是StandardEngineValve,那么它是何时添加到StandardEngine的StandardPipeline中的呢?还记得《Tomcat7.0源码分析——SERVER.XML文件的加载与解析》一文在介绍过的ObjectCreateRule?在执行ObjectCreateRule的begin方法时,会反射调用StandardEngine的构造器生成StandardEngine的实例,StandardEngine的构造器中就会给其StandardPipeline设置basic为StandardEngineValve,见代码清单4。

代码清单4

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Create a new StandardEngine component with the default basic Valve. 
  3.  */  
  4. public StandardEngine() {  
  5.   
  6.     super();  
  7.     pipeline.setBasic(new StandardEngineValve());  
  8.     /* Set the jmvRoute using the system property jvmRoute */  
  9.     try {  
  10.         setJvmRoute(System.getProperty("jvmRoute"));  
  11.     } catch(Exception ex) {  
  12.     }  
  13.     // By default, the engine will hold the reloading thread  
  14.     backgroundProcessorDelay = 10;  
  15.   
  16. }  

代码清单1中最后调用了StandardEngineValve的invoke方法(见代码清单5)正式将请求交给管道处理。根据《Tomcat7.0源码分析——请求原理分析(中)》一文对postParseRequest方法的介绍,request已经被映射到相对应的Context容器(比如/manager)。此处首先调用request的getHost方法(实质是通过request映射的Context容器获取父容器得到,见代码清单6)获取Host容器,然后调用Host容器的Pipeline的getFirst方法获得AccessLogValve。AccessLogValve的invoke方法(见代码清单7),从中可以看出调用了getNext方法获取Host容器的Pipeline的下一个Valve,并调用其invoke方法。

代码清单5

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2. public final void invoke(Request request, Response response)  
  3.     throws IOException, ServletException {  
  4.   
  5.     // Select the Host to be used for this Request  
  6.     Host host = request.getHost();  
  7.     if (host == null) {  
  8.         response.sendError  
  9.             (HttpServletResponse.SC_BAD_REQUEST,  
  10.              sm.getString("standardEngine.noHost",   
  11.                           request.getServerName()));  
  12.         return;  
  13.     }  
  14.     if (request.isAsyncSupported()) {  
  15.         request.setAsyncSupported(host.getPipeline().isAsyncSupported());  
  16.     }  
  17.   
  18.     // Ask this Host to process this request  
  19.     host.getPipeline().getFirst().invoke(request, response);  
  20.   
  21. }  

代码清单6

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public Host getHost() {  
  2.     if (getContext() == null)  
  3.         return null;  
  4.     return (Host) getContext().getParent();  
  5.     //return ((Host) mappingData.host);  
  6. }  

代码清单7

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2. public void invoke(Request request, Response response) throws IOException,  
  3.         ServletException {  
  4.     final String t1Name = AccessLogValve.class.getName()+".t1";  
  5.     if (getState().isAvailable() && getEnabled()) {                  
  6.         // Pass this request on to the next valve in our pipeline  
  7.         long t1 = System.currentTimeMillis();  
  8.         boolean asyncdispatch = request.isAsyncDispatching();  
  9.         if (!asyncdispatch) {  
  10.             request.setAttribute(t1Name, new Long(t1));  
  11.         }  
  12.   
  13.         getNext().invoke(request, response);  
  14.   
  15.         //we're not done with the request  
  16.         if (request.isAsyncDispatching()) {  
  17.             return;  
  18.         } else if (asyncdispatch && request.getAttribute(t1Name)!=null) {  
  19.             t1 = ((Long)request.getAttribute(t1Name)).longValue();  
  20.         }  
  21.           
  22.         long t2 = System.currentTimeMillis();  
  23.         long time = t2 - t1;  
  24.   
  25.         log(request,response, time);  
  26.     } else  
  27.         getNext().invoke(request, response);         
  28. }  

根据以上分析,我们看到StandardEngine容器的Pipeline中只有一个Valve(StandardEngineValve),而StandardHost容器中有三个Valve(分别是AccessLogValve、ErrorReportValve和StandardHostValve),此外StandardContext容器中有一个Valve(StandardContextValve),StandardWrapper中也只有一个Valve(StandardWrapperValve)。这些阀门Valve通过invoke方法彼此串联起来,最终构成的执行顺序十分类似于一个管道,最终形成的管道正如图2一样,这也许是Pipeline名字的由来。


图2  Tomcat管道示意图

本文以StandardEngineValve和AccessLogValve为例讲了Valve的实现,以及Pipeline是如何串联起来的,我们最后看看StandardWrapperValve的实现,其它Valve的实现不再赘述。

Filter与职责链模式

  根据对管道和阀门的分析, 我们知道要分析StandardWrapperValve,只需直接阅读其invoke方法即可,见代码清单8所示。

代码清单8

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2. public final void invoke(Request request, Response response)  
  3.     throws IOException, ServletException {  
  4.   
  5.     // Initialize local variables we may need  
  6.     boolean unavailable = false;  
  7.     Throwable throwable = null;  
  8.     // This should be a Request attribute...  
  9.     long t1=System.currentTimeMillis();  
  10.     requestCount++;  
  11.     StandardWrapper wrapper = (StandardWrapper) getContainer();  
  12.     Servlet servlet = null;  
  13.     Context context = (Context) wrapper.getParent();  
  14.       
  15.     // 省略校验及次要代码  
  16.   
  17.     // Allocate a servlet instance to process this request  
  18.     try {  
  19.         if (!unavailable) {  
  20.             servlet = wrapper.allocate();  
  21.         }  
  22.     } catch (UnavailableException e) {  
  23.         // 省略异常处理代码  
  24.     } catch (ServletException e) {  
  25.         // 省略异常处理代码  
  26.     } catch (Throwable e) {  
  27.         // 省略异常处理代码  
  28.     }  
  29.   
  30.     // Identify if the request is Comet related now that the servlet has been allocated  
  31.     boolean comet = false;  
  32.     if (servlet instanceof CometProcessor   
  33.             && request.getAttribute("org.apache.tomcat.comet.support") == Boolean.TRUE) {  
  34.         comet = true;  
  35.         request.setComet(true);  
  36.     }  
  37.       
  38.     // Acknowledge the request  
  39.     try {  
  40.         response.sendAcknowledgement();  
  41.     } catch (IOException e) {  
  42.         // 省略异常处理代码  
  43.     } catch (Throwable e) {  
  44.         // 省略异常处理代码  
  45.     }  
  46.     MessageBytes requestPathMB = request.getRequestPathMB();  
  47.     DispatcherType dispatcherType = DispatcherType.REQUEST;  
  48.     if (request.getDispatcherType()==DispatcherType.ASYNC) dispatcherType = DispatcherType.ASYNC;   
  49.     request.setAttribute  
  50.         (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,  
  51.          dispatcherType);  
  52.     request.setAttribute  
  53.         (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR,  
  54.          requestPathMB);  
  55.     // Create the filter chain for this request  
  56.     ApplicationFilterFactory factory =  
  57.         ApplicationFilterFactory.getInstance();  
  58.     ApplicationFilterChain filterChain =  
  59.         factory.createFilterChain(request, wrapper, servlet);  
  60.       
  61.     // Reset comet flag value after creating the filter chain  
  62.     request.setComet(false);  
  63.   
  64.     // Call the filter chain for this request  
  65.     // NOTE: This also calls the servlet's service() method  
  66.     try {  
  67.         String jspFile = wrapper.getJspFile();  
  68.         if (jspFile != null)  
  69.             request.setAttribute(Globals.JSP_FILE_ATTR, jspFile);  
  70.         else  
  71.             request.removeAttribute(Globals.JSP_FILE_ATTR);  
  72.         if ((servlet != null) && (filterChain != null)) {  
  73.             // Swallow output if needed  
  74.             if (context.getSwallowOutput()) {  
  75.                 try {  
  76.                     SystemLogHandler.startCapture();  
  77.                     if (request.isAsyncDispatching()) {  
  78.                         //TODO SERVLET3 - async  
  79.                         ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch();   
  80.                     } else if (comet) {  
  81.                         filterChain.doFilterEvent(request.getEvent());  
  82.                         request.setComet(true);  
  83.                     } else {  
  84.                         filterChain.doFilter(request.getRequest(),   
  85.                                 response.getResponse());  
  86.                     }  
  87.                 } finally {  
  88.                     String log = SystemLogHandler.stopCapture();  
  89.                     if (log != null && log.length() > 0) {  
  90.                         context.getLogger().info(log);  
  91.                     }  
  92.                 }  
  93.             } else {  
  94.                 if (request.isAsyncDispatching()) {  
  95.                     //TODO SERVLET3 - async  
  96.                     ((AsyncContextImpl)request.getAsyncContext()).doInternalDispatch();  
  97.                 } else if (comet) {  
  98.                     request.setComet(true);  
  99.                     filterChain.doFilterEvent(request.getEvent());  
  100.                 } else {  
  101.                     filterChain.doFilter  
  102.                         (request.getRequest(), response.getResponse());  
  103.                 }  
  104.             }  
  105.   
  106.         }  
  107.         request.removeAttribute(Globals.JSP_FILE_ATTR);  
  108.     } catch (ClientAbortException e) {  
  109.         // 省略异常处理代码  
  110.     } catch (IOException e) {  
  111.         // 省略异常处理代码  
  112.     } catch (UnavailableException e) {  
  113.         // 省略异常处理代码  
  114.     } catch (ServletException e) {  
  115.         // 省略异常处理代码  
  116.     } catch (Throwable e) {  
  117.         // 省略异常处理代码  
  118.     }  
  119.   
  120.     // Release the filter chain (if any) for this request  
  121.     if (filterChain != null) {  
  122.         if (request.isComet()) {  
  123.             // If this is a Comet request, then the same chain will be used for the  
  124.             // processing of all subsequent events.  
  125.             filterChain.reuse();  
  126.         } else {  
  127.             filterChain.release();  
  128.         }  
  129.     }  
  130.   
  131.     // Deallocate the allocated servlet instance  
  132.     try {  
  133.         if (servlet != null) {  
  134.             wrapper.deallocate(servlet);  
  135.         }  
  136.     } catch (Throwable e) {  
  137.         // 省略异常处理代码  
  138.         }  
  139.     }  
  140.   
  141.     // If this servlet has been marked permanently unavailable,  
  142.     // unload it and release this instance  
  143.     try {  
  144.         if ((servlet != null) &&  
  145.             (wrapper.getAvailable() == Long.MAX_VALUE)) {  
  146.             wrapper.unload();  
  147.         }  
  148.     } catch (Throwable e) {  
  149.         // 省略异常处理代码  
  150.     }  
  151.     long t2=System.currentTimeMillis();  
  152.   
  153.     long time=t2-t1;  
  154.     processingTime += time;  
  155.     if( time > maxTime) maxTime=time;  
  156.     if( time < minTime) minTime=time;  
  157.   
  158. }  

通过阅读代码清单8,我们知道StandardWrapperValve的invoke方法的执行步骤如下:

  1. 调用StandardWrapper的allocate方法分配org.apache.catalina.servlets.DefaultServlet的实例处理访问包括*.html、*.htm、*.gif、*.jpg、*.jpeg等资源的request,分配org.apache.jasper.servlet.JspServlet的实例处理访问*.jpg页面的request。简单提下这些Servlet实例是在StandardContext启动的时候调用StandardWrapper的load方法用反射生成的,有关StandardContext启动的内容可以参考《Tomcat7.0源码分析——生命周期管理》一文。
  2. 确认当前request是否是Comet的,由于默认的DefaultServlet并未实现CometProcessor接口,所以不会作为Comet的请求处理。顺便简单提下,Comet 指的是一种 Web 应用程序的架构。在这种架构中,客户端程序(通常是浏览器)不需要显式的向服务器端发出请求,服务器端会在其数据发生变化的时候主动的将数据异步的发送给客户端,从而使得客户端能够及时的更新用户界面以反映服务器端数据的变化。
  3. 向客户端发送确认。
  4. 给request对象设置请求类型和请求路径属性。
  5. 获取ApplicationFilterFactory(单例模式实现),并调用其createFilterChain方法创建ApplicationFilterChain。
  6. 调用ApplicationFilterChain的doFilter方法,执行ApplicationFilterChain中维护的Filter职责链。
  7. 调用ApplicationFilterChain的release方法清空对Servlet、Filter的引用。
  8. 调用StandardWrapper的deallocate方法释放为其分配的Servlet。
注意:如果接收请求的Servlet实现了SingleThreadModel接口,那么singleThreadModel属性为true,则Tomcat的StandardWrapper中只有一个Servlet实例,否则会创建一个Servlet实例池。创建Filter职责链用到createFilterChain方法,其实现见代码清单9。

代码清单9

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public ApplicationFilterChain createFilterChain  
  2.     (ServletRequest request, Wrapper wrapper, Servlet servlet) {  
  3.   
  4.     // get the dispatcher type  
  5.     DispatcherType dispatcher = null;   
  6.     if (request.getAttribute(DISPATCHER_TYPE_ATTR) != null) {  
  7.         dispatcher = (DispatcherType) request.getAttribute(DISPATCHER_TYPE_ATTR);  
  8.     }  
  9.     String requestPath = null;  
  10.     Object attribute = request.getAttribute(DISPATCHER_REQUEST_PATH_ATTR);  
  11.       
  12.     if (attribute != null){  
  13.         requestPath = attribute.toString();  
  14.     }  
  15.       
  16.     // If there is no servlet to execute, return null  
  17.     if (servlet == null)  
  18.         return (null);  
  19.   
  20.     boolean comet = false;  
  21.       
  22.     // Create and initialize a filter chain object  
  23.     ApplicationFilterChain filterChain = null;  
  24.     if (request instanceof Request) {  
  25.         Request req = (Request) request;  
  26.         comet = req.isComet();  
  27.         if (Globals.IS_SECURITY_ENABLED) {  
  28.             // Security: Do not recycle  
  29.             filterChain = new ApplicationFilterChain();  
  30.             if (comet) {  
  31.                 req.setFilterChain(filterChain);  
  32.             }  
  33.         } else {  
  34.             filterChain = (ApplicationFilterChain) req.getFilterChain();  
  35.             if (filterChain == null) {  
  36.                 filterChain = new ApplicationFilterChain();  
  37.                 req.setFilterChain(filterChain);  
  38.             }  
  39.         }  
  40.     } else {  
  41.         // Request dispatcher in use  
  42.         filterChain = new ApplicationFilterChain();  
  43.     }  
  44.   
  45.     filterChain.setServlet(servlet);  
  46.   
  47.     filterChain.setSupport  
  48.         (((StandardWrapper)wrapper).getInstanceSupport());  
  49.   
  50.     // Acquire the filter mappings for this Context  
  51.     StandardContext context = (StandardContext) wrapper.getParent();  
  52.     FilterMap filterMaps[] = context.findFilterMaps();  
  53.   
  54.     // If there are no filter mappings, we are done  
  55.     if ((filterMaps == null) || (filterMaps.length == 0))  
  56.         return (filterChain);  
  57.   
  58.     // Acquire the information we will need to match filter mappings  
  59.     String servletName = wrapper.getName();  
  60.   
  61.     // Add the relevant path-mapped filters to this filter chain  
  62.     for (int i = 0; i < filterMaps.length; i++) {  
  63.         if (!matchDispatcher(filterMaps[i] ,dispatcher)) {  
  64.             continue;  
  65.         }  
  66.         if (!matchFiltersURL(filterMaps[i], requestPath))  
  67.             continue;  
  68.         ApplicationFilterConfig filterConfig = (ApplicationFilterConfig)  
  69.             context.findFilterConfig(filterMaps[i].getFilterName());  
  70.         if (filterConfig == null) {  
  71.             // FIXME - log configuration problem  
  72.             continue;  
  73.         }  
  74.         boolean isCometFilter = false;  
  75.         if (comet) {  
  76.             try {  
  77.                 isCometFilter = filterConfig.getFilter() instanceof CometFilter;  
  78.             } catch (Exception e) {  
  79.                 // Note: The try catch is there because getFilter has a lot of   
  80.                 // declared exceptions. However, the filter is allocated much  
  81.                 // earlier  
  82.             }  
  83.             if (isCometFilter) {  
  84.                 filterChain.addFilter(filterConfig);  
  85.             }  
  86.         } else {  
  87.             filterChain.addFilter(filterConfig);  
  88.         }  
  89.     }  
  90.   
  91.     // Add filters that match on servlet name second  
  92.     for (int i = 0; i < filterMaps.length; i++) {  
  93.         if (!matchDispatcher(filterMaps[i] ,dispatcher)) {  
  94.             continue;  
  95.         }  
  96.         if (!matchFiltersServlet(filterMaps[i], servletName))  
  97.             continue;  
  98.         ApplicationFilterConfig filterConfig = (ApplicationFilterConfig)  
  99.             context.findFilterConfig(filterMaps[i].getFilterName());  
  100.         if (filterConfig == null) {  
  101.             // FIXME - log configuration problem  
  102.             continue;  
  103.         }  
  104.         boolean isCometFilter = false;  
  105.         if (comet) {  
  106.             try {  
  107.                 isCometFilter = filterConfig.getFilter() instanceof CometFilter;  
  108.             } catch (Exception e) {  
  109.                 // Note: The try catch is there because getFilter has a lot of   
  110.                 // declared exceptions. However, the filter is allocated much  
  111.                 // earlier  
  112.             }  
  113.             if (isCometFilter) {  
  114.                 filterChain.addFilter(filterConfig);  
  115.             }  
  116.         } else {  
  117.             filterChain.addFilter(filterConfig);  
  118.         }  
  119.     }  
  120.   
  121.     // Return the completed filter chain  
  122.     return (filterChain);  
  123.   
  124. }  

根据代码清单9,我们整理下整个创建Filter职责链的过程:

  1. 从request中获取请求的类型(Tomcat目前提供的请求类型有REQUEST、FORWARD、INCLUDE、ASYNC及ERROR五种)与路径;
  2. 创建ApplicationFilterChain并设置给当前request;
  3. 给ApplicationFilterChain设置Servlet,即DefaultServlet;
  4. 从StandardContext中获取当前Context的filterMaps;
  5. 如果filterMaps为空,则说明当前Context没有配置Filter,否则会将filterMaps中的Filter全部添加到ApplicationFilterChain中的Filter职责链中。
   调用ApplicationFilterChain的doFilter方法,执行ApplicationFilterChain中维护的Filter职责链。Filter职责链是对职责链模式的经典应用,我们先通过图3来介绍其执行流程。


图3  Tomcat的Filter职责链执行流程

这里对图3的执行过程进行介绍:

  1. StandardWrapperValve的invoke方法在创建完ApplicationFilterChain后,第一次调用ApplicationFilterChain的doFilter方法;
  2. 如果ApplicationFilterChain自身维护的Filter数组中还有没有执行的Filter,则取出此Filter并执行Filter的doFilter方法(即第3步),否则执行Servlet的service方法处理请求(即第4步);
  3. 每个Filter首先执行自身的过滤功能,最后在执行结束前会回调ApplicationFilterChain的doFilter方法,此时会将执行流程交给第2步;
  4. Servlet的service实际会调用自身的doGet、doHead、doPost、doPut、doDelete等方法。
第2步对应了图3中M.N这个标记的M部分,第3步则对应N的部分。本文最后从源码实现级别分析Filter职责链的执行过程,首先来看ApplicationFilterChain的doFilter方法,见代码清单10。

代码清单10

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public void doFilter(ServletRequest request, ServletResponse response)  
  2.     throws IOException, ServletException {  
  3.   
  4.     if( Globals.IS_SECURITY_ENABLED ) {  
  5.         final ServletRequest req = request;  
  6.         final ServletResponse res = response;  
  7.         try {  
  8.             java.security.AccessController.doPrivileged(  
  9.                 new java.security.PrivilegedExceptionAction<Void>() {  
  10.                     public Void run()   
  11.                         throws ServletException, IOException {  
  12.                         internalDoFilter(req,res);  
  13.                         return null;  
  14.                     }  
  15.                 }  
  16.             );  
  17.         } catch( PrivilegedActionException pe) {  
  18.             Exception e = pe.getException();  
  19.             if (e instanceof ServletException)  
  20.                 throw (ServletException) e;  
  21.             else if (e instanceof IOException)  
  22.                 throw (IOException) e;  
  23.             else if (e instanceof RuntimeException)  
  24.                 throw (RuntimeException) e;  
  25.             else  
  26.                 throw new ServletException(e.getMessage(), e);  
  27.         }  
  28.     } else {  
  29.         internalDoFilter(request,response);  
  30.     }  
  31. }  

从代码清单10看到ApplicationFilterChain的doFilter方法主要调用了internalDoFilter方法(见代码清单11)。

代码清单11

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private void internalDoFilter(ServletRequest request,   
  2.                               ServletResponse response)  
  3.     throws IOException, ServletException {  
  4.   
  5.     // Call the next filter if there is one  
  6.     if (pos < n) {  
  7.         ApplicationFilterConfig filterConfig = filters[pos++];  
  8.         Filter filter = null;  
  9.         try {  
  10.             filter = filterConfig.getFilter();  
  11.             support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT,  
  12.                                       filter, request, response);  
  13.               
  14.             if (request.isAsyncSupported() && "false".equalsIgnoreCase(  
  15.                     filterConfig.getFilterDef().getAsyncSupported())) {  
  16.                 request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,  
  17.                         Boolean.FALSE);  
  18.             }  
  19.             if( Globals.IS_SECURITY_ENABLED ) {  
  20.                 final ServletRequest req = request;  
  21.                 final ServletResponse res = response;  
  22.                 Principal principal =   
  23.                     ((HttpServletRequest) req).getUserPrincipal();  
  24.   
  25.                 Object[] args = new Object[]{req, res, this};  
  26.                 SecurityUtil.doAsPrivilege  
  27.                     ("doFilter", filter, classType, args, principal);  
  28.                   
  29.                 args = null;  
  30.             } else {    
  31.                 filter.doFilter(request, response, this);  
  32.             }  
  33.   
  34.             support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT,  
  35.                                       filter, request, response);  
  36.         } catch (IOException e) {  
  37.             if (filter != null)  
  38.                 support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT,  
  39.                                           filter, request, response, e);  
  40.             throw e;  
  41.         } catch (ServletException e) {  
  42.             if (filter != null)  
  43.                 support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT,  
  44.                                           filter, request, response, e);  
  45.             throw e;  
  46.         } catch (RuntimeException e) {  
  47.             if (filter != null)  
  48.                 support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT,  
  49.                                           filter, request, response, e);  
  50.             throw e;  
  51.         } catch (Throwable e) {  
  52.             if (filter != null)  
  53.                 support.fireInstanceEvent(InstanceEvent.AFTER_FILTER_EVENT,  
  54.                                           filter, request, response, e);  
  55.             throw new ServletException  
  56.               (sm.getString("filterChain.filter"), e);  
  57.         }  
  58.         return;  
  59.     }  
  60.   
  61.     // We fell off the end of the chain -- call the servlet instance  
  62.     try {  
  63.         if (ApplicationDispatcher.WRAP_SAME_OBJECT) {  
  64.             lastServicedRequest.set(request);  
  65.             lastServicedResponse.set(response);  
  66.         }  
  67.   
  68.         support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT,  
  69.                                   servlet, request, response);  
  70.         if (request.isAsyncSupported()  
  71.                 && !support.getWrapper().isAsyncSupported()) {  
  72.             request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,  
  73.                     Boolean.FALSE);  
  74.         }  
  75.         // Use potentially wrapped request from this point  
  76.         if ((request instanceof HttpServletRequest) &&  
  77.             (response instanceof HttpServletResponse)) {  
  78.                   
  79.             if( Globals.IS_SECURITY_ENABLED ) {  
  80.                 final ServletRequest req = request;  
  81.                 final ServletResponse res = response;  
  82.                 Principal principal =   
  83.                     ((HttpServletRequest) req).getUserPrincipal();  
  84.                 Object[] args = new Object[]{req, res};  
  85.                 SecurityUtil.doAsPrivilege("service",  
  86.                                            servlet,  
  87.                                            classTypeUsedInService,   
  88.                                            args,  
  89.                                            principal);     
  90.                 args = null;  
  91.             } else {    
  92.                 servlet.service(request, response);  
  93.             }  
  94.         } else {  
  95.             servlet.service(request, response);  
  96.         }  
  97.         support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT,  
  98.                                   servlet, request, response);  
  99.     } catch (IOException e) {  
  100.         support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT,  
  101.                                   servlet, request, response, e);  
  102.         throw e;  
  103.     } catch (ServletException e) {  
  104.         support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT,  
  105.                                   servlet, request, response, e);  
  106.         throw e;  
  107.     } catch (RuntimeException e) {  
  108.         support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT,  
  109.                                   servlet, request, response, e);  
  110.         throw e;  
  111.     } catch (Throwable e) {  
  112.         support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT,  
  113.                                   servlet, request, response, e);  
  114.         throw new ServletException  
  115.           (sm.getString("filterChain.servlet"), e);  
  116.     } finally {  
  117.         if (ApplicationDispatcher.WRAP_SAME_OBJECT) {  
  118.             lastServicedRequest.set(null);  
  119.             lastServicedResponse.set(null);  
  120.         }  
  121.     }  
  122.   
  123. }  

执行Servlet

从代码清单11,我们可以看到ApplicationFilterChain最后会执行Servlet的service方法,此service方法实际是所有Servlet的父类HttpServlet实现的,见代码清单12。

代码清单12

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2. public void service(ServletRequest req, ServletResponse res)  
  3.     throws ServletException, IOException {  
  4.   
  5.     HttpServletRequest  request;  
  6.     HttpServletResponse response;  
  7.       
  8.     try {  
  9.         request = (HttpServletRequest) req;  
  10.         response = (HttpServletResponse) res;  
  11.     } catch (ClassCastException e) {  
  12.         throw new ServletException("non-HTTP request or response");  
  13.     }  
  14.     service(request, response);  
  15. }  

代码清单12中的service方法调用重载的service方法,后者通过判断HttpServletRequest对象的HTTP Method,调用不同的方法,如GET、DELETE、POST等,见代码清单13。

代码清单13

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. protected void service(HttpServletRequest req, HttpServletResponse resp)  
  2.     throws ServletException, IOException {  
  3.   
  4.     String method = req.getMethod();  
  5.   
  6.     if (method.equals(METHOD_GET)) {  
  7.         long lastModified = getLastModified(req);  
  8.         if (lastModified == -1) {  
  9.             // servlet doesn't support if-modified-since, no reason  
  10.             // to go through further expensive logic  
  11.             doGet(req, resp);  
  12.         } else {  
  13.             long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);  
  14.             if (ifModifiedSince < (lastModified / 1000 * 1000)) {  
  15.                 // If the servlet mod time is later, call doGet()  
  16.                 // Round down to the nearest second for a proper compare  
  17.                 // A ifModifiedSince of -1 will always be less  
  18.                 maybeSetLastModified(resp, lastModified);  
  19.                 doGet(req, resp);  
  20.             } else {  
  21.                 resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);  
  22.             }  
  23.         }  
  24.   
  25.     } else if (method.equals(METHOD_HEAD)) {  
  26.         long lastModified = getLastModified(req);  
  27.         maybeSetLastModified(resp, lastModified);  
  28.         doHead(req, resp);  
  29.   
  30.     } else if (method.equals(METHOD_POST)) {  
  31.         doPost(req, resp);  
  32.           
  33.     } else if (method.equals(METHOD_PUT)) {  
  34.         doPut(req, resp);          
  35.           
  36.     } else if (method.equals(METHOD_DELETE)) {  
  37.         doDelete(req, resp);  
  38.           
  39.     } else if (method.equals(METHOD_OPTIONS)) {  
  40.         doOptions(req,resp);  
  41.           
  42.     } else if (method.equals(METHOD_TRACE)) {  
  43.         doTrace(req,resp);  
  44.           
  45.     } else {  
  46.         //  
  47.         // Note that this means NO servlet supports whatever  
  48.         // method was requested, anywhere on this server.  
  49.         //  
  50.   
  51.         String errMsg = lStrings.getString("http.method_not_implemented");  
  52.         Object[] errArgs = new Object[1];  
  53.         errArgs[0] = method;  
  54.         errMsg = MessageFormat.format(errMsg, errArgs);  
  55.           
  56.         resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);  
  57.     }  
  58. }  

以doGet方法为例,见代码清单14。

代码清单14

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  2.     throws ServletException, IOException  
  3. {  
  4.     String protocol = req.getProtocol();  
  5.     String msg = lStrings.getString("http.method_get_not_supported");  
  6.     if (protocol.endsWith("1.1")) {  
  7.         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);  
  8.     } else {  
  9.         resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);  
  10.     }  
  11. }  

不对啊!为什么doGet方法的实现只是返回了400和405错误呢?因为这是抽象类HttpServlet的默认实现,用户必须实现自身的Servlet或者使用默认的DefaultServlet。 

http://blog.csdn.net/beliefer/article/details/51894747

0 0
原创粉丝点击