源碼深度解析SpringMvc請求運行機制,springmvc運行機制
本文依賴的是springmvc4.0.5.RELEASE,通過源碼深度解析瞭解springMvc的請求運行機制。通過源碼我們可以知道從用戶端發送一個URL請求給springMvc開始,到返回資料給用戶端期間是怎麼運轉的。
1、使用者請求處理過程:
1、使用者發送請求時會先從DispathcherServler的doService方法開始,在該方法中會將ApplicationContext、localeResolver、themeResolver等對象添加到request中,緊接著就是調用doDispatch方法:
源碼:
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {if (logger.isDebugEnabled()) {String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : "";logger.debug("DispatcherServlet with name '" + getServletName() + "'" + resumed +" processing " + request.getMethod() + " request for [" + getRequestUri(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<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));}}}// Make framework objects available to handlers and view objects. <strong>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());</strong>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 {<strong>doDispatch(request, response);</strong>}finally {if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {return;}// Restore the original attribute snapshot, in case of an include.if (attributesSnapshot != null) {restoreAttributesAfterInclude(request, attributesSnapshot);}}}
doDispatch方法就是處理使用者請求的方法。
2、進入該方法後首先會檢查該請求是否是檔案上傳的請求(校正的規則是是否是post並且contenttType是否為multipart/為首碼)即調用的是checkMultipart方法;如果是的將request封裝成MultipartHttpServletRequest。見源碼:
doDispatch:
processedRequest = checkMultipart(request);
checkMultipart:
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {if (request instanceof MultipartHttpServletRequest) {logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +"this typically results from an additional MultipartFilter in web.xml");}else if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) instanceof MultipartException) {logger.debug("Multipart resolution failed for current request before - " +"skipping re-resolution for undisturbed error rendering");}else {return this.multipartResolver.resolveMultipart(request);}}// If not returned before: return original request.return request;}3、然後調用getHandler方法來匹配每個HandlerMapping對象,如果匹配成功會返回這個Handle的處理鏈HandlerExecutionChain對象,在擷取該對象的內部其實也擷取我們自定定義的攔截器,並執行了其中的方法
見源碼:
doDispatch:
HandlerExecutionChain mappedHandler = null;mappedHandler = getHandler(processedRequest);
getHandler方法:
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {for (HandlerMapping hm : this.handlerMappings) {if (logger.isTraceEnabled()) {logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");}HandlerExecutionChain handler = hm.getHandler(request);if (handler != null) {return handler;}}return null;}
hm.getHandler方法:
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {Object handler = getHandlerInternal(request);if (handler == null) {handler = getDefaultHandler();}if (handler == null) {return null;}// Bean name or resolved handler?if (handler instanceof String) {String handlerName = (String) handler;handler = getApplicationContext().getBean(handlerName);}return getHandlerExecutionChain(handler, request);}getHandlerExecutionChain:
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?(HandlerExecutionChain) handler : new HandlerExecutionChain(handler));chain.addInterceptors(getAdaptedInterceptors());String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);for (MappedInterceptor mappedInterceptor : this.mappedInterceptors) {if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {chain.addInterceptor(mappedInterceptor.getInterceptor());}}return chain;}4、執行攔截器的preHandle方法,如果返回false執行afterCompletion方法並理解返回
5、通過上述擷取到了HandlerExecutionChain對象,通過該對象的getHandler()方法獲得一個object通過HandlerAdapter進行封裝得到HandlerAdapter對象
6、該對象調用handle方法來執行Controller中的方法,該對象如果返回一個ModelAndView給DispatcherServlet
7、DispatcherServlet藉助ViewResolver完成邏輯試圖名到真實視圖對象的解析,得到View後DispatcherServlet使用這個View對ModelAndView中的模型資料進行視圖渲染
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。