天天看點

SpringMVC源碼解析從service到doDispatch(下)HttpServlet#serviceFrameworkServlet#processRequestDispatcherServlet#doService後續流程

HttpServlet#service

protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    //擷取請求類型
    String method = req.getMethod();
    //如果是get請求
    if (method.equals(METHOD_GET)) {
        //檢查是不是開啟了頁面緩存 通過header頭的 Last-Modified/If-Modified-Since
        //擷取Last-Modified的值
        long lastModified = getLastModified(req);
        if (lastModified == -1) {
            // servlet doesn't support if-modified-since, no reason
            // to go through further expensive logic
            //沒有開啟頁面緩存調用doGet方法
            doGet(req, resp);
        } else {
            long ifModifiedSince;
            try {
                //擷取If-Modified-Since的值
                ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
            } catch (IllegalArgumentException iae) {
                ifModifiedSince = -1;
            }
            if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                // If the servlet mod time is later, call doGet()
                // Round down to the nearest second for a proper compare
                // A ifModifiedSince of -1 will always be less
                //更新Last-Modified
                maybeSetLastModified(resp, lastModified);
                //調用doGet方法
                doGet(req, resp);
            } else {
                //設定304狀态碼 在HttpServletResponse中定義了很多常用的狀态碼
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            }
        }
    } else if (method.equals(METHOD_HEAD)) {
        //調用doHead方法
        long lastModified = getLastModified(req);
        maybeSetLastModified(resp, lastModified);
        doHead(req, resp);
    } else if (method.equals(METHOD_POST)) {
        //調用doPost方法
        doPost(req, resp);
    } else if (method.equals(METHOD_PUT)) {
       //調用doPost方法
        doPut(req, resp);
    } else if (method.equals(METHOD_DELETE)) {
        //調用doPost方法
        doDelete(req, resp);
    } else if (method.equals(METHOD_OPTIONS)) {
        //調用doPost方法
        doOptions(req,resp);
    } else if (method.equals(METHOD_TRACE)) {
        //調用doPost方法
        doTrace(req,resp);
    } else {
        //伺服器不支援的方法 直接傳回錯誤資訊
        String errMsg = lStrings.getString("http.method_not_implemented");
        Object[] errArgs = new Object[1];
        errArgs[0] = method;
        errMsg = MessageFormat.format(errMsg, errArgs);
        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
    }
}      

根據請求類型調用響應的請求方法如果GET類型,調用doGet方法

POST類型,調用doPost方法。

這些方法都是在HttpServlet中定義的,平時我們做web開發的時候主要是繼承HttpServlet這個類,然後重寫它的doPost或者doGet方法。

我們的FrameworkServlet這個子類就重寫了這些方法中的一部分:doGet、doPost、doPut、doDelete、doOption、doTrace。

這裡我們隻說我們最常用的doGet和doPost這兩個方法。通過翻開源碼我們發現,這兩個方法體的内容是一樣的,都是調用了processRequest

FrameworkServlet#processRequest

protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
 
    long startTime = System.currentTimeMillis();
    Throwable failureCause = null;
    LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
    //國際化
    LocaleContext localeContext = buildLocaleContext(request);
    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    //建構ServletRequestAttributes對象
    ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
    //異步管理
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
    //初始化ContextHolders
    initContextHolders(request, localeContext, requestAttributes);
    //執行doService
    try {
        doService(request, response);
    }
    finally {
        //重新設定ContextHolders
        resetContextHolders(request, previousLocaleContext, previousAttributes);
        if (requestAttributes != null) {
            requestAttributes.requestCompleted();
        }
        //釋出請求處理事件
        publishRequestHandledEvent(request, response, startTime, failureCause);
    }
}      

國際化的設定,建立ServletRequestAttributes對象,初始化上下文holders(即将Request對象放入到線程上下文中),調用doService方法。

國際化的設定

DispatcherServlet#buildLocaleContext這個方法中完成的,其源碼如下:

protected LocaleContext buildLocaleContext(final HttpServletRequest request) {
    if (this.localeResolver instanceof LocaleContextResolver) {
        return ((LocaleContextResolver) this.localeResolver).resolveLocaleContext(request);
    }
    else {
        return new LocaleContext() {
            @Override
            public Locale getLocale() {
                return localeResolver.resolveLocale(request);
            }
        };
    }
}      

沒有配置國際化解析器的話,那麼它會使用預設的解析器:AcceptHeaderLocaleResolver,即從Header中擷取國際化的資訊。

除了AcceptHeaderLocaleResolver之外,SpringMVC中還提供了這樣的幾種解析器:CookieLocaleResolver、SessionLocaleResolver、FixedLocaleResolver。分别從cookie、session中去國際化資訊和JVM預設的國際化資訊(Local.getDefault())。

initContextHolders這個方法主要是将Request請求、ServletRequestAttribute對象和國際化對象放入到上下文中。其源碼如下:

private void initContextHolders(
        HttpServletRequest request, LocaleContext localeContext, RequestAttributes requestAttributes) {
    if (localeContext != null) {
        LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);//threadContextInheritable預設為false
    }
    if (requestAttributes != null) {//threadContextInheritable預設為false
        RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
    }
}      

RequestContextHolder這個類有什麼用呢?有時候我們想在某些類中擷取HttpServletRequest對象,比如在AOP攔截的類中,那麼我們就可以這樣來擷取Request的對象了,

HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);      

DispatcherServlet#doService

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> attributesSnapshot = null;
    if (WebUtils.isIncludeRequest(request)) {
        attributesSnapshot = new HashMap<String, Object>();
        Enumeration<?> attrNames = request.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) {
                attributesSnapshot.put(attrName, request.getAttribute(attrName));
            }
        }
    }
    //Spring上下文
    request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
    //國際化解析器
    request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
    //主題解析器
    request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
    //主題
    request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
    //重定向的資料
    FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
    if (inputFlashMap != null) {
        request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
    }
    request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
    request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);

    try {
        //調用doDispatch方法-核心方法
        doDispatch(request, response);
    }
    finally {
        if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
            // Restore the original attribute snapshot, in case of an include.
            if (attributesSnapshot != null) {
                restoreAttributesAfterInclude(request, attributesSnapshot);
            }
        }
    }
}      

處理include标簽的請求,将上下文放到request的屬性中,将國際化解析器放到request的屬性中,将主題解析器放到request屬性中,将主題放到request的屬性中,處理重定向的請求資料最後調用doDispatch這個核心的方法對請求進行處理

後續流程