springMVC源码笔记
springMVC 设计总览
下图来源:https://www.cnblogs.com/fangjian0423/p/springMVC-directory-summary.html
下图来源:https://www.cnblogs.com/sunniest/p/4555801.html
核心类DispatcherServlet
接收请求DispatcherServlet也是一个Servlet
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
...
try {
this.doDispatch(request, response);
} finally {
if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted() && attributesSnapshot != null) {
this.restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
...
mappedHandler = this.getHandler(processedRequest);
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
...
mappedHandler.applyPreHandle(processedRequest, response)
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
...
this.applyDefaultViewName(request, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
this.processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
HandlerAdapter是一个适配器,根据handler适配ModelAndView
getHandler(processedRequest)是为了获取HandlerExecutionChain:protected HandlerExecutionChain getHandler(HttpServletRequest request)
HandlerExecutionChain 有什么:
private static final Log logger = LogFactory.getLog(HandlerExecutionChain.class);
private final Object handler;
private HandlerInterceptor[] interceptors;
private List<HandlerInterceptor> interceptorList;
private int interceptorIndex;
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (this.getInterceptors() != null) {
for(int i = 0; i < this.getInterceptors().length; this.interceptorIndex = i++) {
HandlerInterceptor interceptor = this.getInterceptors()[i];
if (!interceptor.preHandle(request, response, this.handler)) {
this.triggerAfterCompletion(request, response, (Exception)null);
return false;
}
}
}
return true;
}
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception {
if (this.getInterceptors() != null) {
for(int i = this.getInterceptors().length - 1; i >= 0; --i) {
HandlerInterceptor interceptor = this.getInterceptors()[i];
interceptor.postHandle(request, response, this.handler, mv);
}
}
}
HandlerInterceptor:拦截器(在handler处理前后执行applyPreHandle,applyPostHandle方法)
handler:处理器