spring 源码分析 请求流程 (DispatcherServlet)

spring mvc 请求流程:

1、获取所有HandlerMapping , 通过ServletRequest 请求获取HandlerExecutionChain 对象. (其中封装着HandlerMethod, HandlerInterceptor[] )
2、获取所有HandlerAdapter , 通过 HandlerExecutionChain 中的HandlerMethod获取到对应的Adapter
3、执行HandlerExecutionChain 中所有拦截器 HandlerInterceptor 的前置处理方法 preHandle()
4、使用适配器HandlerAdapter,执行 handle() 方法返回视图 ModelAndView 对象
5、执行HandlerExecutionChain 中所有拦截器 HandlerInterceptor 的后置处理方法 postHandle()
6、然后处理执行结果,是一个 ModelAndView 或 Exception,然后进行渲染

源码 org.springframework.web.servlet.DispatcherServlet 核心方法 doDispatch():
	/**
	 * org.springframework.web.servlet.DispatcherServlet
	 * spring mvc 请求过程:
	 */
	protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpServletRequest processedRequest = request;
		HandlerExecutionChain mappedHandler = null;   //管理执行链
		boolean multipartRequestParsed = false;    //文件上传请求解析

		//获取当前请求的WebAsyncManager,如果没找到则创建并与请求关联
		WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

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

			try {
				//检查是否含Multipart, 有则将请求转换为 Multipart 请求
				processedRequest = checkMultipart(request);
				//含有文件上传功能
				multipartRequestParsed = (processedRequest != request);

				// 遍历所有的 HandlerMapping 找到与请求对应的 Handler,并将其与一堆拦截器封装到 HandlerExecutionChain 对象中
				mappedHandler = getHandler(processedRequest);
				if (mappedHandler == null) {
					//如果没有持有者, 抛出404错误
					noHandlerFound(processedRequest, response);
					return;
				}

				// 遍历所有的 HandlerAdapter,找到可以处理该 Handler 的 HandlerAdapter
				HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

				// 处理请求方法
				String method = request.getMethod();
				boolean isGet = "GET".equals(method); //get请求
				if (isGet || "HEAD".equals(method)) {
					// 获取HandlerExecutionChain => Object => HandlerMethod
					long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
					if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
						return;
					}
				}

				// 遍历拦截器,执行它们的 preHandle() 方法
				if (!mappedHandler.applyPreHandle(processedRequest, response)) {
					return;
				}

				// 执行实际的处理程序, 使用 HandlerAdapter => RequestMappingHandlerAdapter 处理获取 ModelAndView 视图
				mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

				//当前web异步管理是否当前启动管理
				if (asyncManager.isConcurrentHandlingStarted()) {
					return;
				}

				// 应用默认视图名称, 视图为空不做操作
				applyDefaultViewName(processedRequest, mv);
				// 遍历拦截器,执行它们的 postHandle() 方法
				mappedHandler.applyPostHandle(processedRequest, response, mv);
			} catch (Exception ex) {
				dispatchException = ex;
			} catch (Throwable err) {
				// 从4.3开始,我们也在处理处理程序方法抛出的错误,
				// 使它们可用于@ExceptionHandler方法和其他场景
				dispatchException = new NestedServletException("Handler dispatch failed", err);
			}

			// 处理执行结果,是一个 ModelAndView 或 Exception,然后进行渲染
			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 {
			//web异步管理是否处理异步状态
			if (asyncManager.isConcurrentHandlingStarted()) {
				// 映射管理不为空时
				if (mappedHandler != null) {
					// 遍历拦截器,执行它们的 afterCompletion() 方法
					mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
				}
			} else {
				// 清理文件上传请求使用的任何资源
				if (multipartRequestParsed) {
					cleanupMultipart(processedRequest);
				}
			}
		}
	}
真正的请求第一步, FrameworkServlet # processRequest()
	/**
	 * 处理此请求,不管结果如何发布事件
	 * <p>实际的事件处理由抽象的{@link #doService}模板方法执行
	 */
	protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//处理开始时间
		long startTime = System.currentTimeMillis();
		Throwable failureCause = null;

		//返回与当前线程相关联的 LocaleContext
		LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
		//根据请求构建 LocaleContext,公开请求的语言环境为当前语言环境
		LocaleContext localeContext = buildLocaleContext(request);

		//获取当前本次请求的 RequestAttributes
		RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
		//创建 RequestAttributes , 封装request, response
		ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

		//1、获取 WebAsyncManager, 如果没有则创建 WebAsyncManager 并储存.   (request 中请求属性 => WebAsyncManager.WEB_ASYNC_MANAGER)
		//2、给 WebAsyncManager 注册请求回调拦截对象 (RequestBindingInterceptor)
		WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
		asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

		//设置 LocaleContext 和 requestAttributes 到对应的上下文
		initContextHolders(request, localeContext, requestAttributes);

		try {
			//模板模式, 子类去实现
			doService(request, response);
		}
		catch (ServletException | IOException ex) {
			failureCause = ex;
			throw ex;
		}
		catch (Throwable ex) {
			failureCause = ex;
			throw new NestedServletException("Request processing failed", ex);
		}

		finally {
			// 重置 LocaleContext 和 requestAttributes,解除关联
			resetContextHolders(request, previousLocaleContext, previousAttributes);
			if (requestAttributes != null) {
				requestAttributes.requestCompleted();
			}
			logResult(request, response, failureCause, asyncManager);
			//发布 ServletRequestHandlerEvent 请求事件
			publishRequestHandledEvent(request, response, startTime, failureCause);
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值