摘要:前言繼上一篇深入淺出流程解析介紹了后,本文按照深入淺出流程解析的分析流程,繼續(xù)往下分析,介紹下相關(guān)的內(nèi)容。即適配類型為的處理器,對應(yīng)。之前在問答社區(qū)發(fā)現(xiàn)很多的問題都集中再這塊。中的就是通過適配的附錄類圖
前言
繼上一篇【深入淺出spring】Spring MVC 流程解析 -- HanndlerMapping介紹了handler mapping后,本文按照【深入淺出spring】Spring MVC 流程解析的分析流程,繼續(xù)往下分析,介紹下HandlerAdapter相關(guān)的內(nèi)容。
總流程回顧下DispatcherServlet.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 { processedRequest = checkMultipart(request); multipartRequestParsed = (processedRequest != request); // Determine handler for the current request. mappedHandler = getHandler(processedRequest); if (mappedHandler == null) { noHandlerFound(processedRequest, response); return; } // Determine handler adapter for the current request. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // Process last-modified header, if supported by the handler. String method = request.getMethod(); boolean isGet = "GET".equals(method); if (isGet || "HEAD".equals(method)) { long lastModified = ha.getLastModified(request, mappedHandler.getHandler()); if (logger.isDebugEnabled()) { logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified); } if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) { return; } } if (!mappedHandler.applyPreHandle(processedRequest, response)) { return; } // Actually invoke the handler. mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); if (asyncManager.isConcurrentHandlingStarted()) { return; } applyDefaultViewName(processedRequest, mv); 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); } 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()) { // Instead of postHandle and afterCompletion if (mappedHandler != null) { mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response); } } else { // Clean up any resources used by a multipart request. if (multipartRequestParsed) { cleanupMultipart(processedRequest); } } } }
從源碼可以看到,17行根據(jù)request拿到對象HandlerExecutionChain(包含一個處理器 handler 如HandlerMethod 對象、多個 HandlerInterceptor 攔截器對象)后,就是24行根據(jù)handler獲取對應(yīng)的adapter,并在44行調(diào)用適配器的handler方法(適配器設(shè)計模式可以自行g(shù)oogle了解),返回ModelAndView。詳細看下getHandlerAdapter這個方法:
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException { if (this.handlerAdapters != null) { for (HandlerAdapter ha : this.handlerAdapters) { if (logger.isTraceEnabled()) { logger.trace("Testing handler adapter [" + ha + "]"); } if (ha.supports(handler)) { return ha; } } } throw new ServletException("No adapter for handler [" + handler + "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler"); }
和上文handler mapping的邏輯非常類似,遍歷容器中的所有HandlerAdapter,然后判斷是否支持適配此handler,這里的關(guān)鍵方法supports是接口HandlerAdapter中的方法,具體邏輯由其實現(xiàn)類決定。默認的HandlerAdapter的實現(xiàn)類有3種:
RequestMappingHandlerAdapter
HttpRequestHandlerAdapter
SimpleControllerHandlerAdapter
RequestMappingHandlerAdapter 適配哪類處理器RequestMappingHandlerAdapter沒有重寫supports方法,即執(zhí)行的是其父類AbstractHandlerMethodAdapter的方法,代碼如下:
public final boolean supports(Object handler) { return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler)); }
其中supportInternal由子類RequestMappingHandlerAdapter實現(xiàn),直接返回常量true,故可以認為只要handler屬于HandlerMethod類型,就由RequestMappingHandlerAdapter來適配。即RequestMappingHandlerAdapter適配類型為HandlerMethod的處理器,對應(yīng)RequestMappingHandlerMapping。
處理邏輯RequestMappingHandlerAdapter的處理邏輯主要由handleInternal實現(xiàn):
protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception { ModelAndView mav; checkRequest(request); // Execute invokeHandlerMethod in synchronized block if required. if (this.synchronizeOnSession) { HttpSession session = request.getSession(false); if (session != null) { Object mutex = WebUtils.getSessionMutex(session); synchronized (mutex) { mav = invokeHandlerMethod(request, response, handlerMethod); } } else { // No HttpSession available -> no mutex necessary mav = invokeHandlerMethod(request, response, handlerMethod); } } else { // No synchronization on session demanded at all... mav = invokeHandlerMethod(request, response, handlerMethod); } if (!response.containsHeader(HEADER_CACHE_CONTROL)) { if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) { applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers); } else { prepareResponse(response); } } return mav; }
可以看到,核心處理邏輯由方法invokeHandlerMethod實現(xiàn),這塊處理邏輯比較復(fù)雜,涉及輸入?yún)?shù)的解析,返回數(shù)據(jù)的處理,后面一篇文章【深入淺出spring】Spring MVC 流程解析 -- InvocableHandlerMethod會重點講這塊。之前在問答社區(qū)發(fā)現(xiàn)很多spring mvc的問題都集中再這塊。
HttpRequestHandlerAdapter 適配哪類處理器@Override public boolean supports(Object handler) { return (handler instanceof HttpRequestHandler); }
源碼很簡單,適配類型為HttpRequestHandler的處理器
處理邏輯@Override @Nullable public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { ((HttpRequestHandler) handler).handleRequest(request, response); return null; }
處理邏輯也很簡單,直接調(diào)用HttpRequestHandler.handleRequest方法,這里不是通過返回數(shù)據(jù)實現(xiàn)和前端交互,而是直接通過改寫HttpServletResponse實現(xiàn)前后端交互
SimpleControllerHandlerAdapter 適配哪類處理器@Override public boolean supports(Object handler) { return (handler instanceof Controller); }
這里的Controller是一個接口,即所有實現(xiàn)Controller接口的類,SimpleControllerHandlerAdapter都適配
處理邏輯@Override @Nullable public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return ((Controller) handler).handleRequest(request, response); }
和HttpRequestHandlerAdapter類似,直接調(diào)用Controller.handleRequest,即具體實現(xiàn)類的handleRequest方法,然后支持直接返回數(shù)據(jù)來和前端交互。
handler_mapping_sample中的SimpleUrlController就是通過SimpleControllerHandlerAdapter適配的
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/68918.html
摘要:概述是目前主流的框架之一。這部分的詳細分析見深入淺出流程解析調(diào)用的具體方法處理請求,并返回一個。這部分的詳細分析見深入淺出流程解析視圖解析,遍歷的列表,獲取對應(yīng)的對象,入口方法渲染,調(diào)用中獲取的的方法,完成對數(shù)據(jù)的渲染。 前言 其實一年前就想系統(tǒng)地記錄下自己閱讀spring源碼的收獲,搞一個深入淺出spring的系列文章,但是因為工作原因,遲遲沒有下筆。今天終于可以開始自己一年前的計劃...
摘要:問題來了,我們到底還在用嗎答案是,不全用。后者是初始化的配置,主要是的配置。啟動類測試啟動項目后,在瀏覽器里面輸入。通過查詢已裝載的,并且支持該而獲取的。按照前面對的描述,對于而言,這個必定是。的核心在的方法中。 之前已經(jīng)分析過了Spring的IOC(《零基礎(chǔ)帶你看Spring源碼——IOC控制反轉(zhuǎn)》)與AOP(《從源碼入手,一文帶你讀懂Spring AOP面向切面編程》)的源碼,本次...
摘要:是一個基于的框架??刂破鲗⒁晥D響應(yīng)給用戶通過視圖展示給用戶要的數(shù)據(jù)或處理結(jié)果。有了減少了其它組件之間的耦合度。 相關(guān)閱讀: 本文檔和項目代碼地址:https://github.com/zhisheng17/springmvc 轉(zhuǎn)載請注明出處和保留以上文字! 了解 Spring: Spring 官網(wǎng):http://spring.io/ 一個好的東西一般都會有一個好的文檔解釋說明,如果你...
摘要:源碼倉庫本文倉庫三層結(jié)構(gòu)表現(xiàn)層模型業(yè)務(wù)層持久層工作流程用戶前端控制器用戶發(fā)送請求前端控制器后端控制器根據(jù)用戶請求查詢具體控制器后端控制器前端控制器處理后結(jié)果前端控制器視圖視圖渲染視圖前端控制器返回視圖前端控制器用戶響應(yīng)結(jié) SpringMvc 【源碼倉庫】【本文倉庫】 三層結(jié)構(gòu) 表現(xiàn)層 MVC模型 業(yè)務(wù)層 service 持久層 dao 工作流程 用戶->前端控制器:用戶...
閱讀 2849·2021-11-19 09:40
閱讀 3709·2021-11-15 18:10
閱讀 3290·2021-11-11 16:55
閱讀 1246·2021-09-28 09:36
閱讀 1663·2021-09-22 15:52
閱讀 3376·2019-08-30 14:06
閱讀 1171·2019-08-29 13:29
閱讀 2318·2019-08-26 17:04