在Spring MVC中DispatcherServlet负责调用各个上文中的组件来完成对HTTP请求的处理.它是整个Spring MVC流程的总览,了解了DispatcherServlet的处理逻辑基本上了解了整个Spring MVC对于http请求处理的整个流程
image.png
FrameworkServlet
从类继承关系图上来看DispatcherServlet继承了FrameworkServlet类,这里使用了模板设计模式规定所有子类的基本执行过程.在这个类中有两个方法是比较重要的,分别是processRequest跟doService方法,前者定义所有是定义所有子类的处理http请求行为模板,后者是留给子类根据自己需要实现不同的行为.
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
Throwable failureCause = null;
// 将http跟local信息放进ThreadLocal中方便后续访问
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
LocaleContext localeContext = buildLocaleContext(request);
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
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 {
// 清理ThreadLocal内的信息防止内存泄漏以及下次请求获取local,request等信息错乱
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
// 将请求结果打印到日志中
logResult(request, response, failureCause, asyncManager);
// 发布携带http处理请求结果的event
// 如果需要记录http请求日志的话可以使用spring事件处理监听这个event
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
我们从processRequest方法我们知道DispatcherServlet处理http的前后动作,接下来我们看一下DispatcherServlet对于自身需要对于doService方法的实现.doService方法的实现比较清晰且逻辑十分简单,分为以下几个步骤
- 打印Http请求信息日志
- 获取所有request attribute放进用于请求结束后恢复到处理http请求前的request attribute状态
- 解析flash attribute并更新.(其实flash attribute跟request attribute差别不大都是放置访问属性值,但前者可以多个请求共享而后者仅当前请求有效,前者将属性值放入到session)
- doDispatch() 本文重点具体处理http请求的实现
- 将http attritube恢复到处理前的状态
DispatcherServlet 处理http请求具体流程
doDispatch方法基本上是spring mvc处理的http请求的基本流程,明白它之后基本上明白了一半了
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
// 封装http处理结果以及要跳转的模板引擎视图
ModelAndView mv = null;
// 如果我们编写拦截器跟controller方法发生异常会被这个引用捕获
Exception dispatchException = null;
try {
// 判断是否是文件上传并解析文件
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// 获取调用链路
// 它由HandlerInterceptor跟handler组成
// 前者可以对执行处理前后做一些统一处理 如果我们用注解的话后者是我们编写的业务代码方法的具体封装
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
// 找不到调用链路的话直接404
noHandlerFound(processedRequest, response);
return;
}
// 获取一个适配器来执行调用链路,因为spring mvc支持多种开发模式,我们常用的注解开发只是其中一种
// 如果是处理我们平时的使用的注解开发的话会返回RequestMappingHandlerAdapter
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// spring mvc对于http协议:服务器核对请求资源的最后修改时间以及http请求头的etag判断浏览器缓存的资源版本是否有效,如果有效的话告诉浏览器有效并停止响应
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;
}
}
// 执行我们编写的HandlerInterceptor的前置动作preHandle方法,如果返回false的话代表前置调用(检查不符合业务条件)后续我们编写的其他HandlerInterceptor跟controller方法也不会被执行
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 设配器设计模式: 设配器执行handler的逻辑
// 我们平时编写的controller方法会在这里转载方法参数并执行
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
// 根据需要设置默认要跳转的视图模板引擎
// 执行HandlerInterceptor后置动作postHandle方法
applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// 执行HandlerInterceptor的最终步骤afterCompletion方法
// 处理执行结果跳转到相关模板引擎视图以及异常处理等等
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
// 保证HandlerInterceptor的afterCompletion因为所有的拦截器的前置步骤返回true一定执行
// 即使我们编写的controller方法跟HandlerInterceptor后置方法postHandle发生异常
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);
}
}
}
}
我们从代码可以知道doDispatch方法的执行流程包括:
- 判断文件上传并解析
- 获取调用链路HandlerExecutionChain
- 获取一个合适执行handler的设配器用于后面执行我们编写的业务代码
- 对http协议的Last-Modified跟eTag的支持
- 通过调用HandlerInterceptor的preHandle方法来达到统一前置校验
- 使用前面获取的设配器来调用我们编写的业务代码
- 通过调用HandlerInterceptor的postHandle方法来达到统一后续执行步骤
- 处理我们业务代码的执行结果跳转到模板引擎视图,业务异常处理,以及调用HandlerInterceptor的afterCompletion达到资源关闭等目的.