最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringMVC中的DispatcherServlet請求分析

 更新時間:2024年01月05日 09:07:11   作者:it_lihongmin  
這篇文章主要介紹了SpringMVC中的DispatcherServlet請求分析, DispatcherServlet作為一個Servlet,那么當有請求到Tomcat等Servlet服務器時,會調用其service方法,再調用到其父類GenericServlet的service方法,需要的朋友可以參考下

一、service請求(servlet請求轉換為Http請求)

DispatcherServlet作為一個Servlet,那么當有請求到Tomcat等Servlet服務器時,會調用其service方法。再調用到其父類GenericServlet的service方法,HttpServlet中實現(xiàn),如下(開始請求的調用):

@Override
public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {
    HttpServletRequest  request;
    HttpServletResponse response;
    try {
        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;
    } catch (ClassCastException e) {
        throw new ServletException(lStrings.getString("http.non_http"));
    }
    service(request, response);
}

HttpServlet層:將request和response類型進行轉換后,繼續(xù)調用service方法:

protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
 
    String method = req.getMethod();
    
    if (method.equals(METHOD_GET)) {
        long lastModified = getLastModified(req);
        if (lastModified == -1) {
            // servlet doesn't support if-modified-since, no reason
            // to go through further expensive logic
            doGet(req, resp);
        } else {
            long ifModifiedSince;
            try {
                ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
            } catch (IllegalArgumentException iae) {
                // Invalid date header - proceed as if none was set
                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
                maybeSetLastModified(resp, lastModified);
                doGet(req, resp);
            } else {
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            }
        }
 
    } else if (method.equals(METHOD_HEAD)) {
        long lastModified = getLastModified(req);
        maybeSetLastModified(resp, lastModified);
        doHead(req, resp);
    } else if (method.equals(METHOD_POST)) {
        doPost(req, resp);
    } else if (method.equals(METHOD_PUT)) {
        doPut(req, resp);
    } else if (method.equals(METHOD_DELETE)) {
        doDelete(req, resp);
    } else if (method.equals(METHOD_OPTIONS)) {
        doOptions(req,resp);
    } else if (method.equals(METHOD_TRACE)) {
        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);
    }
}

根據(jù)調用的Http請求的方式,調用具體的底層(FrameworkServlet層)方法,get、post請求等都會有相同的處理,比如doGet如下:

@Override
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}
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 requestAttributes = buildRequestAttributes(request, response, previousAttributes);
 
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
 
    initContextHolders(request, localeContext, requestAttributes);
 
    try {
        doService(request, response);
    } catch (ServletException | IOException ex) {
        failureCause = ex;
        throw ex;
    } catch (Throwable ex) {
        failureCause = ex;
        throw new NestedServletException("Request processing failed", ex);
    } finally {
        resetContextHolders(request, previousLocaleContext, previousAttributes);
        if (requestAttributes != null) {
            requestAttributes.requestCompleted();
        }
        logResult(request, response, failureCause, asyncManager);
        publishRequestHandledEvent(request, response, startTime, failureCause);
    }
}

主要的核心邏輯為doService,但是Tomcat是使用線程池的方式接受來自客戶端的請求的,當前請求中可能帶有Locate(國際化參數(shù)信息),那么需要使用ThreadLocal在請求前記錄參數(shù)信息,在請求之后finally中將參數(shù)恢復回去,不會影響到下一個請求。

Spring經常會這樣進行處理,比如AopContext等處理Aop切面信息。

二、doService請求(request中添加SpringMVC初始化的九大件信息)

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    logRequest(request);
 
    // Keep a snapshot of the request attributes in case of an include,
    // to be able to restore the original attributes after the include.
    Map<String, Object> attributesSnapshot = null;
    if (WebUtils.isIncludeRequest(request)) {
        attributesSnapshot = new HashMap<>();
        Enumeration<?> attrNames = request.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
                attributesSnapshot.put(attrName, request.getAttribute(attrName));
            }
        }
    }
 
    // Make framework objects available to handlers and view objects.
    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());
 
    if (this.flashMapManager != null) {
        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(request, response);
    }
    finally {
        if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
            // Restore the original attribute snapshot, in case of an include.
            if (attributesSnapshot != null) {
                restoreAttributesAfterInclude(request, attributesSnapshot);
            }
        }
    }
}

1、打印請求日志

2、請求中添加屬性(WebApplicationContext容器,i18n解析器,主題解析器,主題,重定向屬性處理)

3、核心方法 doDispatch

三、doDispatch

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    boolean multipartRequestParsed = false;
    // 異步請求屬性解析(重定向)
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    try {
        ModelAndView mv = null;
        Exception dispatchException = null;
        try {
            // 如果是Multipart上傳文件請求,則調用multipartResolver.resolveMultipart(上傳文件解析器進行解析)
            processedRequest = checkMultipart(request);
            multipartRequestParsed = (processedRequest != request);
 
            // 確定Handler處理該請求(HandlerExecutionChain調用鏈,責任鏈模式)
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null) {
                noHandlerFound(processedRequest, response);
                return;
            }
 
            // 根據(jù)初始化時加載的適配器挨個匹配是否能適配該調用鏈
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
 
            // 對請求頭中的last-modified進行處理
            String method = request.getMethod();
            boolean isGet = "GET".equals(method);
            if (isGet || "HEAD".equals(method)) {
                long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                    return;
                }
            }
            // 對HandlerExecutionChain中的所有HandlerInterceptor調用preHandle方法
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }
 
            // 真正的請求調用
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
 
            if (asyncManager.isConcurrentHandlingStarted()) {
                return;
            }
            // 判斷Controller返回的ModelAndView中是否有View,
            // 沒有則使用viewNameTranslator執(zhí)行沒有試圖的解析規(guī)則
            applyDefaultViewName(processedRequest, mv);
            // 對HandlerExecutionChain中的所有HandlerInterceptor調用postHandle方法
            mappedHandler.applyPostHandle(processedRequest, response, mv);
        } catch (Exception ex) {
            dispatchException = ex;
        } catch (Throwable err) {
            // As of 4.3, we're processing Errors thrown from handler methods as well,
            // making them available for @ExceptionHandler methods and other scenarios.
            dispatchException = new NestedServletException("Handler dispatch failed", err);
        }
        // 處理結果解析(ModelAndView或者Exception),保證最終會執(zhí)行所以Interceptor的triggerAfterCompletion
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    } catch (Exception ex) {
        triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
    } catch (Throwable err) {
        triggerAfterCompletion(processedRequest, response, mappedHandler,
                new NestedServletException("Handler processing failed", err));
    } finally {
        if (asyncManager.isConcurrentHandlingStarted()) {
            // 不知道什么情況下回進入相當于執(zhí)行所以Interceptor的postHandle和afterCompletion方法
            if (mappedHandler != null) {
                mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
            }
        }
        else {
            // 清除當前文件上傳請求的資源
            if (multipartRequestParsed) {
                cleanupMultipart(processedRequest);
            }
        }
    }
}

這里是整個SpringMVC的核心,每個流程都可能會比較復雜,后續(xù)單獨分析。流程如下(主要是標紅的步驟):

1、異步請求屬性解析(重定向)

2、如果是Multipart上傳文件請求,則調用multipartResolver.resolveMultipart(上傳文件解析器進行解析)

4、確定Handler處理該請求(HandlerExecutionChain調用鏈,責任鏈模式)

5、根據(jù)初始化時加載的適配器挨個匹配是否能適配該調用鏈

6、對請求頭中的last-modified進行處理

7、對HandlerExecutionChain中的所有HandlerInterceptor調用preHandle方法

8、真正的請求調用

9、沒有試圖的解析返回

10、對HandlerExecutionChain中的所有HandlerInterceptor調用postHandle方法

11、處理結果解析(ModelAndView或者Exception),保證最終會執(zhí)行所以Interceptor的triggerAfterCompletion

12、清除當前文件上傳請求的資源

HandlerInterceptor方法調用

當我們需要使用Spring的攔截器時,會集實現(xiàn)HandlerInterceptor的preHandle、postHandle、triggerAfterCompletion方法。

當?shù)?步完成后我們獲取到了HandlerExecutionChain調用鏈,其中包括需要執(zhí)行的攔截器和真正調用的方法(后面專門分析專門獲取的)。

但是在上面的步驟看到了對攔截器的三個方法的調用時機,其實每個調用的方法都差不多,就看preHandle方法即可,調用HandlerExecutionChain的applyPreHandle方法如下:

boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HandlerInterceptor[] interceptors = getInterceptors();
    if (!ObjectUtils.isEmpty(interceptors)) {
        for (int i = 0; i < interceptors.length; i++) {
            HandlerInterceptor interceptor = interceptors[i];
            if (!interceptor.preHandle(request, response, this.handler)) {
                triggerAfterCompletion(request, response, null);
                return false;
            }
            this.interceptorIndex = i;
        }
    }
    return true;
}

由于preHandle方法允許返回false則不執(zhí)行真實的Controller方法調用,所以需要每次判斷。但是在執(zhí)行preHandle和postHandle方法時,都允許最后調用一次triggerAfterCompletion方法。都是在拿到調用鏈中的所以有序的攔截器,輪訓調用其對應的方法即可。

到此這篇關于SpringMVC中的DispatcherServlet請求分析的文章就介紹到這了,更多相關DispatcherServlet請求分析內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java中Arrays.asList() 的不可變陷阱

    Java中Arrays.asList() 的不可變陷阱

    本文主要介紹了Arrays.asList()創(chuàng)建的集合不可變原因,指出其底層數(shù)組為final且未重寫修改方法,導致增刪拋異常,下面就來介紹一下Arrays.asList() 陷阱,感興趣的可以了解一下
    2025-06-06
  • 使用IDEA創(chuàng)建SpringBoot項目

    使用IDEA創(chuàng)建SpringBoot項目

    本文詳細介紹了使用SpringBoot創(chuàng)建項目,包含配置、啟動、開發(fā)環(huán)境配置等,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-12-12
  • Java遞歸算法詳解(動力節(jié)點整理)

    Java遞歸算法詳解(動力節(jié)點整理)

    Java遞歸算法是基于Java語言實現(xiàn)的遞歸算法。遞歸算法對解決一大類問題很有效,它可以使算法簡潔和易于理解。接下來通過本文給大家介紹Java遞歸算法相關知識,感興趣的朋友一起學習吧
    2017-03-03
  • 使用log4j2關閉debug日志

    使用log4j2關閉debug日志

    這篇文章主要介紹了使用log4j2關閉debug日志方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • 如何將java或javaweb項目打包為jar包或war包

    如何將java或javaweb項目打包為jar包或war包

    本文主要介紹了如何將java或javaweb項目打包為jar包或war包,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • SpringBoot集成echarts實現(xiàn)k線圖功能

    SpringBoot集成echarts實現(xiàn)k線圖功能

    ECharts是一款基于JavaScript的數(shù)據(jù)可視化圖表庫,提供直觀,生動,可交互,可個性化定制的數(shù)據(jù)可視化圖表,本文給大家介紹了SpringBoot集成echarts實現(xiàn)k線圖功能,文中有詳細的代碼示例供大家參考,需要的朋友可以參考下
    2024-07-07
  • jstack和線程dump實例解析

    jstack和線程dump實例解析

    這篇文章主要介紹了jstack和線程dump實例解析,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • Java設計模式:組合模式

    Java設計模式:組合模式

    這篇文章主要介紹了快速理解Java設計模式中的組合模式,具有一定參考價值,需要的朋友可以了解下,希望能夠給你帶來幫助
    2021-09-09
  • SpringBoot后端進行數(shù)據(jù)校驗JSR303的使用詳解

    SpringBoot后端進行數(shù)據(jù)校驗JSR303的使用詳解

    這篇文章主要介紹了SpringBoot后端進行數(shù)據(jù)校驗JSR303的使用詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • spring中的ObjectPostProcessor詳解

    spring中的ObjectPostProcessor詳解

    這篇文章主要介紹了spring中的ObjectPostProcessor詳解,Spring Security 的 Java 配置不會公開其配置的每個對象的每個屬性,這簡化了大多數(shù)用戶的配置,畢竟,如果每個屬性都公開,用戶可以使用標準 bean 配置,需要的朋友可以參考下
    2024-01-01

最新評論

庆城县| 潼关县| 慈溪市| 伊宁市| 玛沁县| 山西省| 视频| 五华县| 筠连县| 连州市| 铜川市| 黎平县| 湘潭市| 巢湖市| 吉木萨尔县| 巢湖市| 罗江县| 开原市| 大足县| 永丰县| 宽甸| 兰考县| 赣州市| 泽普县| 灵寿县| 周宁县| 舟曲县| 韶山市| 江永县| 班戈县| 彩票| 紫阳县| 肇源县| 大安市| 通许县| 南城县| 安图县| 台安县| 桓仁| 台中市| 白朗县|