SpringMVC工作原理源码分析
首先、当请求进入Tomcat时、在web.xml查找对应的Servlet类、找到DispatcherServlet类并且匹配路径 /、现在创建DispatcherServlet类的示例、并开始执行service方法、即Servlet类的初始方法、DispathcherServlet继承的父类通过调用service方法层层调用至DispatcherServlet类中的doService方法、在由doService方法调用doDispatch方法(核心流程在此方法中)
doDispatch
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
try {
ModelAndView mv = null;
Object dispatchException = null;
try {
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
// 根据url对应的地址查找对应控制器类和方法、没有找到则返回DefaultServletHttpRequestHandler类
mappedHandler = this.getHandler(processedRequest);
if (mappedHandler == null) {
this.noHandlerFound(processedRequest, response);
return;
}
// 控制器适配器
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
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;
}
}
// 检查是否有拦截器、有的话执行拦截器对应的方法.
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 根据url查询到对应的控制器类中的方法、现在由控制器适配器调用该控制器类方法、然后返回控制类方法返回的视图
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
this.applyDefaultViewName(processedRequest, mv);
// 拦截器方法、执行Controller返回后执行
mappedHandler.applyPostHandle(processedRequest, response, mv);
} catch (Exception var20) {
dispatchException = var20;
} catch (Throwable var21) {
dispatchException = new NestedServletException("Handler dispatch failed", var21);
}
this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
} catch (Exception var22) {
this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
} catch (Throwable var23) {
this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
}
} finally {
if (asyncManager.isConcurrentHandlingStarted()) {
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
} else if (multipartRequestParsed) {
this.cleanupMultipart(processedRequest);
}
}
}
标签:SpringMVC,mappedHandler,mv,request,源码,原理,方法,response,processedRequest
From: https://www.cnblogs.com/tie-dao/p/16709923.html