Spring MVC : DispatcherServlet进行请求处理的主逻辑

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/andy_zhang2007/article/details/88620044

Spring MVC前置控制器DispatcherServlet对请求进行处理的主要逻辑体现在其方法doDispatch的实现,如下 :

	/**
	 * Process the actual dispatching to the handler.
	 * 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.
	 * 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;
		// 用于记录针对该请求的请求处理器 handler 以及有关的 HandlerInteceptor , 封装成一个 
		// HandlerExecutionChain, 在随后的逻辑中会被使用
		HandlerExecutionChain mappedHandler = null;
		// 用于标记当前请求是否是一个文件上传请求
		boolean multipartRequestParsed = false;

		WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

		try {
			ModelAndView mv = null;
			Exception dispatchException = null;

			try {
				// 检查请求是否文件上传请求  
				processedRequest = checkMultipart(request);
				// 如果 processedRequest 和  request 不同,说明检测到了文件上传请求过程中
				// 才会出现的内容,现在把这个信息记录在 multipartRequestParsed
				multipartRequestParsed = (processedRequest != request);

				// Determine handler for the current request.
				// 这里根据请求自身,和 DispatcherServlet 的 handlerMappings 查找能够处理该请求的
				// handler, 记录在 mappedHandler , 具体返回的类型是 HandlerExecutionChain ,
				// 相当于 n 个 HandlerInterceptor + 1 个 handler 。
				mappedHandler = getHandler(processedRequest);
				if (mappedHandler == null) {
					// 如果没有找到可以处理该请求的 handler , 这里直接交给 noHandlerFound 处理,
					// 根据配置决定 抛出异常 或者返回 404
					noHandlerFound(processedRequest, response);
					return;
				}

				// Determine handler adapter for the current request.
				// 根据所找到的 handler 和 DispatcherServlet 的 handlerAdapters 看看哪个 handlerAdapter
				// 可以执行这个 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 (new ServletWebRequest(request, response).checkNotModified(lastModified) 
						&& isGet) {
						// 如果是 GET/HEAD 模式,并且发现资源从上次访问到现在没被修改过,则直接返回
						return;
					}
				}

				// 执行 mappedHandler 所有 HandlerInteceptor 的 preHandle 方法,
				// 如果有执行失败,在这里直接返回不再继续处理该请求
				if (!mappedHandler.applyPreHandle(processedRequest, response)) {
					return;
				}

				// Actually invoke the handler.
				// 现在才真正由所找到的 HandlerAdapter  执行 所对应的 handler,
				// 返回结果是一个 ModelAndView 对象 mv, 或者 null
				mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

				if (asyncManager.isConcurrentHandlingStarted()) {
					return;
				}

				// 如果上面获取的 ModelAndView 对象 mv 不为 null, 并且没有含有 view,
				// 并且配置了缺省 view,这里应用缺省 view
				applyDefaultViewName(processedRequest, mv);
              
				// 执行 mappedHandler 所有 HandlerInteceptor 的 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);
			}
			// 处理 handler 结果 ModelAndView mv
			// 1. 根据 view 名称 或者 异常找到最终要使用的 view
			// 2. 渲染 view
			// 3. 执行 mappedHandler 所有 HandlerInteceptor 的 afterCompletion 方法
			processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
		}
		catch (Exception ex) {
			// 异常情况下执行 mappedHandler 所有 HandlerInteceptor 的 afterCompletion 方法
			triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
		}
		catch (Throwable err) {
			// 异常情况下执行 mappedHandler 所有 HandlerInteceptor 的 afterCompletion 方法
			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);
				}
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/88620044