一、继承关系
-
DispatcherServlet
继承FrameworkServlet
-
FrameworkServlet
继承HttpServletBean
-
HttpServletBean
继承HttpServlet
-
HttpServlet
继承GenericServlet
-
enericServlet
实现Servlet
(是一个接口) -
Servlet
的声明周期有三部分: -
- init()
- service()
- destroy()
二、DispatcherServlet
是从日志中发现了DispatcherServlet
这个类。
在这里插入图片描述
2.1 initStrategies
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
- Multipart是和文件相关的,Resolver是解析器
- 本地初始化解析器
- 主体初始化解析器
- 处理器初始化映射
- 处理器初始化适配器
- 处理器初始化
2.2 doDispatch
// 主要代码
// 获得处理器
mappedHandler = getHandler(processedRequest);
// 获得处理器适配器
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// 执行拦截器(预处理阶段),如果返回false就立即停止(被拦截)
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 使用处理器适配器对于处理器进行调度,返回ModelAndView
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
// 拦截器的后处理
mappedHandler.applyPostHandle(processedRequest, response, mv);
// 对于所有资源进行整理
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
2.2.1 doDispatch-applyPreHandle
/**
* Apply preHandle methods of registered interceptors.
* @return {@code true} if the execution chain should proceed with the
* next interceptor or the handler itself. Else, DispatcherServlet assumes
* that this interceptor has already dealt with the response itself.
*/
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
for (int i = 0; i < this.interceptorList.size(); i++) {
HandlerInterceptor interceptor = this.interceptorList.get(i);
if (!interceptor.preHandle(request, response, this.handler)) {
triggerAfterCompletion(request, response, null);
return false;
}
this.interceptorIndex = i;
}
return true;
}
这是一个拦截器链,然后遍历每一个拦截器,对于各个拦截器进行拦截的前置处理。
2.2.2 doDispatch-applyPostHandle
/**
* Apply postHandle methods of registered interceptors.
*/
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
throws Exception {
for (int i = this.interceptorList.size() - 1; i >= 0; i--) {
HandlerInterceptor interceptor = this.interceptorList.get(i);
interceptor.postHandle(request, response, this.handler, mv);
}
}
遍历拦截器链上的每一个拦截器,对于其进行后置拦截处理