写在前面
SpringBoot其实就是SpringMVC的简化版本,对于request的处理流程大致是一样的, 都要经过DispatcherServlet拦截之后通过相应的Handler去寻找对应的Controller处理业务最后返回ModelAndView做视图解析之后渲染到前端页面。
0x01 doDispatch
首先所有请求都会经过org/springframework/web/servlet/DispatcherServlet.java,这一点也可以根据该方法注释了解到。
我们的请求会先进入到DispatcherServlet#doService方法中,在doService中调用了doDispatch,而doDispatch是实现大部分处理request逻辑的地方,大致可分为请求处理(如寻找相应controller,获取ModelAndView,resolveView视图解析等)和页面渲染,下面是该方法代码。
/**
* Process the actual dispatching to the handler.
* <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
* to find the first that supports the handler class.
* <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
* themselves to decide which methods are acceptable.
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception in case of any kind of processing failure
*/
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
//将request对象重新存储到processedRequest
HttpServletRequest processedRequest = request;
//处理器链
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
//获取异步请求管理器
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
//最终返回的ModelAndView对象
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// Process last-modified header, if supported by the handler.
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;
}
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed