1. 说说请求是怎么到DispatcherServlet的doDispatch()方法的
前面一篇文章我们已经分析过了SpringMVC的初始化流程(https://www.jianshu.com/p/b254a45612e8),现在我们继续探究一下SpringMVC的请求处理过程;
首先复习一下,Spring基于Servlet实现的类的继承结构,有了继承结构图,我们就能更好的分析其原理
如你所知,HttpServlet类中有处理请求的doGet(), doPost(), service()等方法,如下图所示
HttpServlet
有了HttpServlet的成员,我们再来看看它具体的实现,下面是HttpServlet接口的部分源码
关键部分都已经在源码中给出说明
public abstract class HttpServlet extends GenericServlet {
/**
* 该方法重写的GenericServlet类中的service()方法,
* GenericServlet 类中的 service()方法是重写的 Servlet 接口的
*
* 该类中的这个方法作用是将 ServletRequest 请求转换为 HttpServletRequest 请求
*/
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
//调用service的重载方法
service(request, response);
}
/**
* 根据传入的 HttpServletRequest 根据请求方式不同,调用不同的方法;
* 比如 method是 GET 请求的话,就会调用doGet(HttpServletRequest req, HttpServletResponse resp) 方法
* 其他的请求方式也是如此
*/
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
// Invalid date header - proceed as if none was set
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
/**
* 如果HttpServletRequest的请求方式是 GET 的话,调用以下方法,
*
* 而Spring在 FrameworkServlet中对doGet()方法进行了实现
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
}
从HttpServlet到FrameworkServlet
从源码可知,FrameworkServlet对部分不同类型的请求进行了实现,那么就来看看FrameworkServlet的源码
@SuppressWarnings("serial")
public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware {
@Override
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected final void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected final void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
Throwable failureCause = null;
//获取与当前线程关联的localeContText对象
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
//Build a LocaleContext for the given request, exposing the request's primary locale as current locale.
//为当前请求构建一个新的LocaleContext对象
LocaleContext localeContext = buildLocaleContext(request);
//获取与当前线程关联的RequestAttributes对象
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
//为当前请求构建一个新的ServletRequestAttributes实例
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(org.springframework.web.servlet.FrameworkServlet.class.getName(), new org.springframework.web.servlet.FrameworkServlet.RequestBindingInterceptor());
//让新构造的localeContext对象,requestAttributes对象与当前请求绑定,通过ThreadLocal完成
initContextHolders(request, localeContext, requestAttributes);
try {
//抽象方法,具体有子类DispatcherServlet实现
doService(request, response);
}
catch (ServletException | IOException ex) {
failureCause = ex;
throw ex;
}
catch (Throwable ex) {
failureCause = ex;
throw new NestedServletException("Request processing failed", ex);
}
finally {
//doService()完成之后,解除localeContext对象,requestAttributes对象与当前请求的绑定
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
if (logger.isDebugEnabled()) {
if (failureCause != null) {
this.logger.debug("Could not complete request", failureCause);
}
else {
if (asyncManager.isConcurrentHandlingStarted()) {
logger.debug("Leaving response open for concurrent processing");
}
else {
this.logger.debug("Successfully completed request");
}
}
}
//通过 new ServletRequestHandledEvent()发布事件
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
}
从FrameworkServlet到DispatcherServlet
从FrameworkServlet源码可知, doGet(), doPost(),doDelete(), doPut()等方法都调用了该类的processRequest()方法;而这个processRequest()方法最重要的就是doService()方法, 而doService()方法是由其子类DispatcherServlet实现的,所以我们不得不去看看DispatcherServlet的源码了;
@SuppressWarnings("serial")
public class DispatcherServlet extends FrameworkServlet {
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isDebugEnabled()) {
String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : "";
logger.debug("DispatcherServlet with name '" + getServletName() + "'" + resumed +
" processing " + request.getMethod() + " request for [" + getRequestUri(request) + "]");
}
// Keep a snapshot of the request attributes in case of an include,
// to be able to restore the original attributes after the include.
//判断请求是不是include请求,如果是include请求就对request的属性做一个备份,放到attributesSnapshot中, 在finally代码块中还原
Map<String, Object> attributesSnapshot = null;
if (WebUtils.isIncludeRequest(request)) {
attributesSnapshot = new HashMap<>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
}
// 设置请求的各种属性
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
//接下来处理 flashMap,如果存在 flashMap 则进行复原
if (this.flashMapManager != null) {
FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
if (inputFlashMap != null) {
request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
}
request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
}
try {
//调用 doDispatch() 方法, 进行请求的分发
doDispatch(request, response);
} finally {
//对备份的属性进行还原。
if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
// Restore the original attribute snapshot, in case of an include.
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
}
}
至此,我们才到了DispatcherServlet处理请求的核心方法了, 至于doDispatch()方法,究竟是怎么处理的呢?
我们继续探究,先贴出doDispatch()的源码
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
//这个用来保存实际上所用的 request 对象,在后面的流程中会对当前 request 对象进行检查,
//如果是文件上传请求,则会对请求重新进行封装,如果不是文件上传请求,则继续使用原来的请求。
HttpServletRequest processedRequest = request;
//这是具体处理请求的处理器链,包括请求处理器和对应的Interceptor;
HandlerExecutionChain mappedHandler = null;
//文件上传请求的标记
boolean multipartRequestParsed = false;
//异步请求管理器
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
//渲染返回的 ModelAndView 对象
ModelAndView mv = null;
//请求处理过程中所抛出的异常,这个异常不包括渲染过程抛出的异常
Exception dispatchException = null;
try {
//检查是不是文件上传请求,如果是则对当前 request 重新进行包装,如果不是,则直接将request返回
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
//获取当前请求的处理器
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
//抛出NoHandlerFoundException异常 或者 在返回404
noHandlerFound(processedRequest, response);
return;
}
//获取当前请求的处理器适配器
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
//处理 GET HEAD 请求中的 Last_Modified 字段;
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (logger.isDebugEnabled()) {
logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
}
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
//拦截器的预处理方法
//如果执行链应继续处理下一个拦截器或处理程序本身,则为true.否则,DispatcherServlet假设这个拦截器已经处理了响应本身。
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
//调用真正的请求,获取到返回结果 mv
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
//是否需要异步处理, 如果需要, 直接return
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
//如果不需要异步处理,则执行 applyDefaultViewName 方法,检查当前 mv 是否没有视图,如果没有(例如方法返回值为 void),则给一个默认的视图名
applyDefaultViewName(processedRequest, mv);
//执行拦截器的postHandle()方法
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", err);
}
//异常处理、渲染页面以及执行拦截器的 afterCompletion()方法
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
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的流程, 原文链接:https://blog.csdn.net/u012702547/article/details/115176519?spm=1001.2014.3001.5501
2. 探究doDispatch()方法中的getHandler(processedRequest)
未完待续