先上一段Spring MVC核心類DispatcherServlet中最重要的方法doDispatch源碼ios
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); // 根據當前請求獲取對應的處理器映射器 mappedHandler = getHandler(processedRequest); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // 根據handler類型獲取對應的處理器適配器 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); } } } }
關注代碼中打中文註釋的兩個地方,一個獲取對應handler的處理器映射器,一個獲取對應handler的處理器適配器。那爲何須要這兩個東西,咱們直接在handler中寫映射邏輯,直接經過handler來執行處理器方法難道不行嗎?答案是否認的,但Spring爲何要這樣作?有如下幾個好處程序員
1.將具體的handler與handlerMapping分離開,爲了符合單一職責app
2.讓具體的處理器與DispatcherServlet解耦合,爲了符合開閉原則
咱們知道全部的處理器映射器都有共同的基類HandlerMapping,這個是能夠肯定的,也是不會改變的。而handler的類型在將來是極有可能變更或繼續追加的。當前版本Spring有如下幾種handler類型:
-HandlerMethod(經過RequestMappingHandlerMapping解析而來,咱們最常使用的)
-Servlet(繼承自Servlet接口的處理器)
-Controller(繼承自Controller接口的處理器)
它們以前並無共同的基類,也不可能有共同的基類,由於它們來自不一樣的包,來自不一樣的設計者。
Spring設計者將DispatcherServlet與HandlerMapping關聯,當追加新的handler類型之後,現有代碼並不須要改動,符合面向對象的又一原則:開閉原則。async
處理器適配器與處理器映射器的做用相似,都是爲了解耦合。post
if(handler instanceof Servlet){ (Servlet)handler.service(); }else if(handler instanceof HandlerMethod){ (ServletInvocableHandlerMethod)handler.invokeAndHandle(); }else if (handler instanceof Controller){ ((Controller) handler).handleRequest(); }
若是咱們要新增一種處理器類型,必然要繼續追寫else if來進行處理,但使用處理器適配器後,DispatcherServlet不須要改動任何代碼,由於它只依賴HandlerAdapter,這樣DispatcherServlet與具體的Handler就解耦合了,它們以前能夠獨立發展。spa
優秀的程序員是藝術家,而藝術就是代碼。debug