Spring MVC請求處理流程及架構
阿新 • • 發佈:2019-01-04
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進行解析 processedRequest = checkMultipart(request); multipartRequestParsed = (processedRequest != request); //通過getHandler()方法,使用HandlerMapping完成請求到處理器的對映,獲取到HandlerExecutionChain // Determine handler for the current request. mappedHandler = getHandler(processedRequest); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } //將獲取到的Handler處理器進行適配,用響應的HandlerAdapter進行包裝 // 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; } } //如果設定了攔截器,那麼在執行handler處理器方法處理之前,進行攔截器預處理 if (!mappedHandler.applyPreHandle(processedRequest, response)) { return; } //通過介面卡呼叫執行處理器的相關功能處理方法,返回ModelAndView物件,包含檢視和Model資料 // Actually invoke the handler. mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); if (asyncManager.isConcurrentHandlingStarted()) { return; } applyDefaultViewName(request, mv); //如果設定了攔截器,那麼在執行handler處理器方法處理之後,進行攔截器後處理 mappedHandler.applyPostHandle(processedRequest, response, mv); } catch (Exception ex) { dispatchException = ex; } //這裡處理請求結果,在個函式中,將判斷是否有dispatchException,如果有,將通過ExceptionResolver進行解析處理。然後由ViewResolver解析View ,最後對View進行渲染呈現檢視 processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); } catch (Exception ex) { triggerAfterCompletion(processedRequest, response, mappedHandler, ex); } catch (Error err) { triggerAfterCompletionWithError(processedRequest, response, mappedHandler, err); } finally { if (asyncManager.isConcurrentHandlingStarted()) { // Instead of postHandle and afterCompletion if (mappedHandler != null) { mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response); } } else { //如果請求是multipart,那麼這裡進行資源清理操作 // Clean up any resources used by a multipart request. if (multipartRequestParsed) { cleanupMultipart(processedRequest); } } } }