不少人會用 SpringMVC,但對它的處理請求的方式並不清楚,當咱們學習一個知識的時候,瞭解它會讓咱們更好地使用它,下面咱們來看看 SpringMVC 是如何處理請求的。前端
先上圖:java
Spring MVC 框架也是一個基於請求驅動的 Web 框架,而且使用了前端控制器模式(是用來提供一個集中的請求處理機制,全部的請求都將由一個單一的處理程序處理來進行設計,再根據請求映射規則分發給相應的頁面控制器(動做/處理器)進行處理。首先讓咱們總體看一下 Spring MVC 處理請求的流程:ios
首先用戶發送請求,請求被 SpringMVC前端控制器(DispatherServlet)捕獲;web
前端控制器(DispatherServlet)對請求 URL 解析獲取請求 URI,根據 URI,調用 HandlerMapping;spring
前端控制器(DispatherServlet)得到返回的 HandlerExecutionChain(包括 Handler 對象以及 Handler 對象對應的攔截器);緩存
DispatcherServlet 根據得到的 HandlerExecutionChain,選擇一個合適的 HandlerAdapter。(附註:若是成功得到 HandlerAdapter 後,此時將開始執行攔截器的 preHandler(...) 方法);app
HandlerAdapter 根據請求的 Handler 適配並執行對應的 Handler;HandlerAdapter 提取 Request 中的模型數據,填充 Handler 入參,開始執行 Handler(Controller)。 在填充 Handler 的入參過程當中,根據配置,Spring 將作一些額外的工做:框架
HttpMessageConveter:將請求消息(如 Json、xml 等數據)轉換成一個對象,將對象轉換爲指定的響應信息;less
數據轉換:對請求消息進行數據轉換。如 String 轉換成 Integer、Double 等;異步
數據格式化:如將字符串轉換成格式化數字或格式化日期等;
數據驗證: 驗證數據的有效性(長度、格式等),驗證結果存儲到 BindingResult 或 Error 中);
Handler 執行完畢,返回一個 ModelAndView (即模型和視圖)給 HandlerAdaptor;
HandlerAdaptor 適配器將執行結果 ModelAndView 返回給前端控制器;
前端控制器接收到 ModelAndView 後,請求對應的視圖解析器;
視圖解析器解析 ModelAndView 後返回對應 View;
渲染視圖並返回渲染後的視圖給前端控制器;
對於 SpringMVC 項目全部的請求入口(靜態資源除外)這裏都是從 web.xml 文件配置的前端控制器 DispatcherServlet 開始:
<!-- servlet請求分發器 --> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:servlet-context.xml</param-value> </init-param> <!-- 表示啓動容器時初始化該Servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <!-- 這是攔截請求, /表明攔截全部請求,攔截全部.do請求 --> <url-pattern>/</url-pattern> </servlet-mapping>
DispatcherServlet UML繼承關係圖以下:
這裏關注藍線部分繼承結構:DispatcherServlet-->FrameworkServlet-->HttpServletBean-->HttpServlet-->GenericServlet-->Servlet,對於請求核心時序圖以下:
對於 web 請求的處理,你們都知道是經過繼承 HttpServlet 重寫其 service 方法,這裏打開 DispatcherServlet 源碼發現這裏並無看到咱們要找的 service 方法,此時到父類 FrameworkServlet 查找以下:能夠看到父類重寫 HttpServlet service 方法。
/** * Override the parent class implementation in order to intercept PATCH requests. */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpMethod httpMethod = HttpMethod.resolve(request.getMethod()); if (httpMethod == HttpMethod.PATCH || httpMethod == null) { proce***equest(request, response); } else { super.service(request, response); } }
從源碼分析來看當請求方法爲 patch 請求或者爲 null 時執行 proce***equest0 方法,其餘狀況則調用父類 service 方法,你們都知道 SpringMVC 請求大多請求是 get|post 請求爲主,此時繼續向上查看 FrameworkServlet 父類 HttpServletBean(抽象類繼承 HttpServlet 並未重寫 service 方法,因此向上繼續尋找)--> HttpServlet service 方法:
@Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; if (!(req instanceof HttpServletRequest && res instanceof HttpServletResponse)) { throw new ServletException("non-HTTP request or response"); } request = (HttpServletRequest) req; response = (HttpServletResponse) res; service(request, response); } } 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 = req.getDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < lastModified) { // 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 { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // 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); } }
能夠看到 HttpServlet service 進行了重載,根據不一樣的請求類型而後調用不一樣處理方法,這裏以 get 請求爲例,當請求方法爲 get 請求時在重載 service 方法中調用 doGet 方法進行處理,這裏須要特別注意的是:HttpServlet 存在 doGet 方法實現,然而在繼承的子類中也存在 doGet 方法實現,到底調用哪一個方法?很明顯調用子類的 doGet 方法(面向對象多態思想!!!)從繼承 UML 關係圖上看,最外層子類實現 doGet 方法的爲 FrameworkServlet :
@Override protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { proce***equest(request, response); } protected final void proce***equest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 系統計時開始時間 long startTime = System.currentTimeMillis(); Throwable failureCause = null; // 國際化 LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); LocaleContext localeContext = buildLocaleContext(request); //構建ServletRequestAttributes對象 RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes); //異步管理 WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor()); //初始化ContextHolders 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 { //恢復原來的LocaleContext和ServiceRequestAttributes到LocaleContextHolder和RequestContextHolder,避免影響Servlet之外的處理,如Filter resetContextHolders(request, previousLocaleContext, previousAttributes); if (requestAttributes != null) { requestAttributes.requestCompleted(); } logResult(request, response, failureCause, asyncManager); //發佈ServletRequestHandlerEvent消息,這個請求是否執行成功都會發布消息的 publishRequestHandledEvent(request, response, startTime, failureCause); } } // initContextHolders(request, localeContext, requestAttributes); private void initContextHolders(HttpServletRequest request, @Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) { if (localeContext != null) { LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable); } if (requestAttributes != null) { RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable); } }
該方法大概作了這幾件事:國際化的設置,建立 ServletRequestAttributes 對象,初始化上下文 holders (即將 Request 對象放入到線程上下文中,如後續想要在方法中獲取 request、response對象此時能夠經過調用 LocaleContextHolder 對應方法便可),而後調用 doService 方法。對於 doService 方法,FrameworkServlet 類並未提供實現,該方法由 DispatcherServlet 子類實現:
DispatcherServlet 裏面執行處理的入口方法是 doService,因爲這個類繼承於 FrameworkServlet 類,重寫了 doService() 方法:
@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)); } } } //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()); //重定向的數據 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 { //request設置完相關的屬性作真正的請求處理 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 這個核心的方法對請求進行處理:
該方法是在 doService 方法中調用的,從底層設計了整個請求的處理流程:
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 { // 校驗是否爲上傳請求 是上傳請求執行解析 不然返回request processedRequest = checkMultipart(request); multipartRequestParsed = (processedRequest != request); // 根據訪問的Handler 返回指定對應的HandlerExecutionChain對象 這裏從HandlerMapping 集合中查找 HandlerExecutionChain 對象包含Handler與攔截器HandlerInterceptor列表 mappedHandler = getHandler(processedRequest); if (mappedHandler == null) { noHandlerFound(processedRequest, response); return; } // 根據獲得的Handler 獲取對應的HandlerAdaptor對象 HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // 處理GET、HEAD請求的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; } } //執行Interceptor的preHandle if (!mappedHandler.applyPreHandle(processedRequest, response)) { return; } // 執行Handler 返回ModelAndView mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); //若是須要異步處理,直接返回 if (asyncManager.isConcurrentHandlingStarted()) { return; } //當view爲空時,根據request設置默認view,如Handler返回值爲void applyDefaultViewName(processedRequest, mv); //執行相應Interceptor的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); } //處理返回結果,包括處理異常、渲染頁面,發出完成通知觸發Interceptor的afterCompletion 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); } } } }
doDispatcher 首先檢查是否是上傳請求,若是是則將 request 轉換爲 MultipartHttpServletRequest,並將 multipartRequestParsed 標誌設置爲 true;
processDispatchResult 方法主要用來處理前面返回的結果,其中包括處理異常、渲染頁面、觸發 Interceptor 的 afterCompletion 方法三部份內容,處理的異常是在處理請求 doDispatch 方法的過程當中產生。
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv, @Nullable Exception exception) throws Exception { boolean errorView = false; // 若是請求過程當中有異常拋出則處理異常 if (exception != null) { if (exception instanceof ModelAndViewDefiningException) { logger.debug("ModelAndViewDefiningException encountered", exception); mv = ((ModelAndViewDefiningException) exception).getModelAndView(); } else { Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, exception); errorView = (mv != null); } } //執行頁面渲染操做 if (mv != null && !mv.wasCleared()) { render(mv, request, response); if (errorView) { WebUtils.clearErrorRequestAttributes(request); } } else { if (logger.isTraceEnabled()) { logger.trace("No view rendering, null ModelAndView returned."); } } if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) { // Concurrent handling started during a forward return; } // Handler請求處理完,觸發Interceptor的afterCompletion if (mappedHandler != null) { // Exception (if any) is already handled.. mappedHandler.triggerAfterCompletion(request, response, null); } }
render 視圖渲染:
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception { // Determine locale for request and apply it to the response. Locale locale = (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale()); response.setLocale(locale); View view; String viewName = mv.getViewName(); if (viewName != null) { // We need to resolve the view name. view = resolveViewName(viewName, mv.getModelInternal(), locale, request); if (view == null) { throw new ServletException("Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" + getServletName() + "'"); } } else { // No need to lookup: the ModelAndView object contains the actual View object. view = mv.getView(); if (view == null) { throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in servlet with name '" + getServletName() + "'"); } } if (logger.isTraceEnabled()) { logger.trace("Rendering view [" + view + "] "); } try { if (mv.getStatus() != null) { response.setStatus(mv.getStatus().value()); } // 渲染頁面處理 view.render(mv.getModelInternal(), request, response); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("Error rendering view [" + view + "]", ex); } throw ex; } }
今天咱們來了解了一下 SpringMVC 框架中 MVC 核心思想,SpringMVC 內部請求流程分析以及源碼級別代碼解讀,讓你們真正可以從底層級別理解整個框架執行原貌,最後以一張圖來總結今天的源碼分析執行流程。
模型-視圖-控制器(MVC)是一個衆所周知的以設計界面應用程序爲基礎的設計思想。它主要經過分離模型、視圖及控制器在應用程序中的角色將業務邏輯從界面中解耦。一般,模型負責封裝應用程序數據在視圖層展現。視圖僅僅只是展現這些數據,不包含任何業務邏輯。控制器負責接收來自用戶的請求,並調用後臺服務(service或者dao)來處理業務邏輯。處理後,後臺業務層可能會返回了一些數據在視圖層展現。控制器收集這些數據及準備模型在視圖層展現。MVC模式的核心思想是將業務邏輯從界面中分離出來,容許它們單獨改變而不會相互影響。