Spring MVC 处理流程 -- doDispatch

237 阅读2分钟

1.png

/**
	 * Process the actual dispatching to the handler.
	 * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
	 * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
	 * to find the first that supports the handler class.
	 * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
	 * themselves to decide which methods are acceptable.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @throws Exception in case of any kind of processing failure
	 */
	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.
                                // **通过getHandler(request) 方法获取当前请求的HandlerExecutionChain**
				mappedHandler = getHandler(processedRequest);
				if (mappedHandler == null) {
                                        // 如果找不到通过noHandlerFound()返回404
					noHandlerFound(processedRequest, response);
					return;
				}

				// Determine handler adapter for the current request.
                                // **通过getHandlerAdapter(HandlerExecutionChain.getHandler()) 获取 HandlerAdapter
				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 (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
						return;
					}
				}

				if (!mappedHandler.applyPreHandle(processedRequest, response)) {
					return;
				}

				// Actually invoke the handler.
                                // **通过handle() 方法执行请求并返回ModelAndView对象**
				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);
				}
			}
		}
	}

流程总结

  1. DispatchServletdoDispatch中调用getHandler(request)获取当前request的HandlerExecutionChain,如果返回为null,则调用noHandlerFound()报404
  2. DispatchServlet中的getHandler(request)是遍历成员变量List<HandlerMapping>,调用HanderMapping中的getHandler(request)去查找HandlerExecutionChain
  3. 调用getHandlerAdapter()获取当前请求的HandlerAdapter
  4. 调用HandlerExecutionChain中的applyPreHandle执行第一次拦截
  5. 执行HandlerAdapterhandle方法返回ModelAndView对象
  6. 调用HandlerExecutionChain中的applyPostHandle执行第二次拦截
  7. 执行processDispatchResult方法,该方法调用render()进行渲染视图
  8. render()调用resolveViewName()方法,该方法调用ViewResolverresolveViewName进行视图处理
  9. HandlerExecutionChain中保存着一个拦截器的List,第一次拦截是从左到右依次调用拦截器的preHnadle方法,在第二次拦截是从右到左依次调用拦截器的postHandle方法,第一次拦截返回值是布尔类型,第二次拦截没有返回值