Tomcat源碼解析系列(十九)ApplicationFilterChain

前言
上篇文章中分析了各個容器相關的 Pipeline 屬性對象的 的 Valve 屬性對象的 invoke 方法。在最後的 StandardWrapperValve 方法裏調用 ApplicationFilterChain#doFilter 方法,本文分析一下這個方法。java


1. ApplicationFilterChain#doFiltersegmentfault

/**
 * Invoke the next filter in this chain, passing the specified request
 * and response.  If there are no more filters in this chain, invoke
 * the <code>service()</code> method of the servlet itself.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response)
    throws IOException, ServletException {

    if( Globals.IS_SECURITY_ENABLED ) {
        final ServletRequest req = request;
        final ServletResponse res = response;
        try {
            java.security.AccessController.doPrivileged(
                new java.security.PrivilegedExceptionAction<Void>() {
                    @Override
                    public Void run()
                        throws ServletException, IOException {
                        internalDoFilter(req,res);
                        return null;
                    }
                }
            );
        } catch( PrivilegedActionException pe) {
            Exception e = pe.getException();
            if (e instanceof ServletException)
                throw (ServletException) e;
            else if (e instanceof IOException)
                throw (IOException) e;
            else if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            else
                throw new ServletException(e.getMessage(), e);
        }
    } else {
        internalDoFilter(request,response);
    }
}

doFilter 方法就是簡單調用 internalDoFilter 方法。
2. ApplicationFilterChain#internalDoFilter數組

/**
 * The int which is used to maintain the current position
 * in the filter chain.
 */
private int pos = 0;


/**
 * The int which gives the current number of filters in the chain.
 */
private int n = 0;

private void internalDoFilter(ServletRequest request,
                              ServletResponse response)
    throws IOException, ServletException {

    // Call the next filter if there is one
    if (pos < n) {
        ApplicationFilterConfig filterConfig = filters[pos++];
        try {
            Filter filter = filterConfig.getFilter();

            if (request.isAsyncSupported() && "false".equalsIgnoreCase(
                    filterConfig.getFilterDef().getAsyncSupported())) {
                request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
            }
            if( Globals.IS_SECURITY_ENABLED ) {
                final ServletRequest req = request;
                final ServletResponse res = response;
                Principal principal =
                    ((HttpServletRequest) req).getUserPrincipal();

                Object[] args = new Object[]{req, res, this};
                SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal);
            } else {
                filter.doFilter(request, response, this);
            }
        } catch (IOException | ServletException | RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            throw new ServletException(sm.getString("filterChain.filter"), e);
        }
        return;
    }

    // We fell off the end of the chain -- call the servlet instance
    try {
        if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
            lastServicedRequest.set(request);
            lastServicedResponse.set(response);
        }

        if (request.isAsyncSupported() && !servletSupportsAsync) {
            request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,
                    Boolean.FALSE);
        }
        // Use potentially wrapped request from this point
        if ((request instanceof HttpServletRequest) &&
                (response instanceof HttpServletResponse) &&
                Globals.IS_SECURITY_ENABLED ) {
            final ServletRequest req = request;
            final ServletResponse res = response;
            Principal principal =
                ((HttpServletRequest) req).getUserPrincipal();
            Object[] args = new Object[]{req, res};
            SecurityUtil.doAsPrivilege("service",
                                       servlet,
                                       classTypeUsedInService,
                                       args,
                                       principal);
        } else {
            servlet.service(request, response);
        }
    } catch (IOException | ServletException | RuntimeException e) {
        throw e;
    } catch (Throwable e) {
        e = ExceptionUtils.unwrapInvocationTargetException(e);
        ExceptionUtils.handleThrowable(e);
        throw new ServletException(sm.getString("filterChain.servlet"), e);
    } finally {
        if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
            lastServicedRequest.set(null);
            lastServicedResponse.set(null);
        }
    }
}

internalDoFilter 方法裏分了兩部分,if (pos < n) 和 if 後面的 try-catch 語句。tomcat

  1. if (pos < n)

先從 filter 是數組裏獲取下一個 ApplicationFilterConfig 對象。app

ApplicationFilterConfig filterConfig = filters[pos++];

而後經過 filterConfig.getFilter() 獲取一個 Filter 對象,並調用這個 Filter 的 doFilter 方法,並把 ApplicationFilterChain 對象傳入 Filter#doFilteride

在 if (pos < n) 裏的 n 是這個 ApplicationFilterChain 裏包含的 Filter 的總數。this

每次調用 internalDoFilter 方法,pos 就加1,也就是獲取下一個 ApplicationFilterConfig,直到 pos 等於 n 的時候纔不執行 if 語句,爲了達到這個效果,應用程序必須在自定義的在 Filter 裏執行 FilterChain#doFilter 方法,才能再次進入 ApplicationFilterChain#internalDoFilter 方法,這樣就完成了調用 ApplicationFilterChain 裏全部的 Filter 的 doFilter 方法。
這種方式是責任鏈模式的一種體現。spa

  1. try-catch

internalDoFilter裏的 try-catch 是在執行完全部的 Filter#doFilter 方法以後執行的。
try 語句塊裏先設置一下屬性,而後執行code

servlet.service(request, response);

經過調用 Servlet 對象的 service 方法來處理請求。對象

到這裏,tomcat 終於把請求交給了應用程序了,tomcat 整個接受請求、轉發處理請求的流程就差很少完結了。


小結本文分析了 ApplicationFilterChain#doFilter 方法,在這個方法裏,tomcat 首先調用了 ApplicationFilterChain 裏全部 Filter 的 doFilter 方法,而後調用 ApplicationFilterChain 裏的 Servlet 對象的 service 方法把請求交給了應用程序。

相關文章
相關標籤/搜索