说明:本文所用的SpringMVC版本为4.3.4.RELEASE,应用服务器为TomCat8.0.33。
前面几篇文章我们简单的分析了一下SpringMVC初始化的过程,接下来的这几篇文章我们从源码的角度分析一下SpringMVC对请求的处理过程。这一篇文章我们来分析请求从service到DispatcherServlet的doDispatch的过程。我们做web开发的同学大都对Servlet的生命周期比较了解,对Servlet规范也有一些了解。我们知道请求在被Servlet处理之前会先被过滤器处理,过滤器处理完之后会调用Servlet的service方法来对相应的请求进行处理响应(关于过滤器可以看这里)。所以我们这里分析的入口是Servlet的service方法。我们在用SpringMVC的时候,通常都会在web.xml中进行这样的配置:
<servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:learn-spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>我们了解Servlet的同学都知道这样配置的话,所有的请求(静态资源除外)将由DispatcherServlet进行处理。即我们这里处理请求的Servlet类是DispatcherServlet。下面首先我们来看一下DispatcherServlet的UML类图:
在上面的类图中我们先关注蓝色线的这一部分,即左面的这一部分内容。从上面的类图中我们可以看到DispatcherServlet继承了FrameworkServlet,FrameworkServlet继承了HttpServletBean,HttpServletBean继承了HttpServlet,HttpServlet继承了GenericServlet,GenericServlet则实现了我们最顶级的接口Servlet和ServletConfig。请求的主要时序图如下:
从DispatcherServlet的源码中我们没有找到service(ServletRequest req, ServletResponse res)这个方法,但是我们在DispatcherServlet的父类HttpServlet中找到了这个方法,我们去HttpServlet中看看这个方法的内容:
HttpServlet#service(ServletRequest req, ServletResponse res)
@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(request, response); } }service这个方法的内容很简单,就是将ServletRequest和ServletResponse转换为HttpServletRequest和HttpServletResponse。因为我们是做web开发,通常用的是HTTP协议,所以这里我们需要的时候HttpServletRequest和HttpServletResponse。接下来就是调用service(HttpServletRequest request, HttpServletResponse response),我们在HttpServlet和FrameworkServlet中都找到了这个方法,但是HttpServlet是FrameworkServlet的父类,即FrameworkServlet中重写了service这个方法,所以我们这里取FrameworkServlet中去看看这个方法的内容:
FrameworkServlet#service(HttpServletRequest request, HttpServletResponse response)
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpMethod httpMethod = HttpMethod.resolve(request.getMethod()); if (HttpMethod.PATCH == httpMethod || httpMethod == null) { processRequest(request, response); } else { super.service(request, response); } }这个方法的内容也很简单,第一步根据请求的方法类型转换对应的枚举类。我们可以看一下HttpMethod这个枚举类:
public enum HttpMethod { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; private static final Map<String, HttpMethod> mappings = new HashMap<String, HttpMethod>(8); static { for (HttpMethod httpMethod : values()) { mappings.put(httpMethod.name(), httpMethod); } } public static HttpMethod resolve(String method) { return (method != null ? mappings.get(method) : null); } public boolean matches(String method) { return (this == resolve(method)); } }HttpMethod这个定义了这样的几种枚举类型:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;而这些也是RFC标准中几种请求类型。如果请求类型为PATCH或者没有找到相应的请求类型的话,则直接调用processRequest这个方法。但是这种情况我们很少很少会遇到。所以这里会执行super.service这个方法。即调用HttpServlet中的service方法。我们看一下HttpServlet中这个service方法的内容:
HttpServlet#service(HttpServletRequest req, HttpServletResponse resp)
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求类型 String method = req.getMethod(); //如果是get请求 if (method.equals(METHOD_GET)) { //检查是不是开启了页面缓存 通过header头的 Last-Modified/If-Modified-Since //获取Last-Modified的值 long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic //没有开启页面缓存调用doGet方法 doGet(req, resp); } else { long ifModifiedSince; try { //获取If-Modified-Since的值 ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); } catch (IllegalArgumentException iae) { 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 //更新Last-Modified maybeSetLastModified(resp, lastModified); //调用doGet方法 doGet(req, resp); } else { //设置304状态码 在HttpServletResponse中定义了很多常用的状态码 resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { //调用doHead方法 long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { //调用doPost方法 doPost(req, resp); } else if (method.equals(METHOD_PUT)) { //调用doPost方法 doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { //调用doPost方法 doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { //调用doPost方法 doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { //调用doPost方法 doTrace(req,resp); } else { //服务器不支持的方法 直接返回错误信息 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); } }这个方法的主要作用是根据请求类型调用响应的请求方法如果GET类型,调用doGet方法;POST类型,调用doPost方法。这些方法都是在HttpServlet中定义的,平时我们做web开发的时候主要是继承HttpServlet这个类,然后重写它的doPost或者doGet方法。我们的FrameworkServlet这个子类就重写了这些方法中的一部分:doGet、doPost、doPut、doDelete、doOption、doTrace。这里我们只说我们最常用的doGet和doPost这两个方法。通过翻开源码我们发现,这两个方法体的内容是一样的,都是调用了processRequest这个方法。processRequest这个方法是我们接下来要分析的:
FrameworkServlet#processRequest(HttpServletRequest request, HttpServletResponse response)
protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); Throwable failureCause = null; LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); //国际化 LocaleContext localeContext = buildLocaleContext(request); RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes(); //构建ServletRequestAttributes对象 ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes); //异步管理 WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor()); //初始化ContextHolders initContextHolders(request, localeContext, requestAttributes); //执行doService try { doService(request, response); } finally { //重新设置ContextHolders resetContextHolders(request, previousLocaleContext, previousAttributes); if (requestAttributes != null) { requestAttributes.requestCompleted(); } //发布请求处理事件 publishRequestHandledEvent(request, response, startTime, failureCause); } }在这个方法里大概做了这样几件事:国际化的设置,创建ServletRequestAttributes对象,初始化上下文holders(即将Request对象放入到线程上下文中),调用doService方法。我们分析主要的几个:
protected LocaleContext buildLocaleContext(final HttpServletRequest request) { if (this.localeResolver instanceof LocaleContextResolver) { return ((LocaleContextResolver) this.localeResolver).resolveLocaleContext(request); } else { return new LocaleContext() { @Override public Locale getLocale() { return localeResolver.resolveLocale(request); } }; } }根据我们之前文章的分析,如果我们没有配置国际化解析器的话,那么它会使用默认的解析器:AcceptHeaderLocaleResolver,即从Header中获取国际化的信息。除了AcceptHeaderLocaleResolver之外,SpringMVC中还提供了这样的几种解析器:CookieLocaleResolver、SessionLocaleResolver、FixedLocaleResolver。分别从cookie、session中去国际化信息和JVM默认的国际化信息(Local.getDefault())。
initContextHolders这个方法主要是将Request请求、ServletRequestAttribute对象和国际化对象放入到上下文中。其源码如下:
private void initContextHolders( HttpServletRequest request, LocaleContext localeContext, RequestAttributes requestAttributes) { if (localeContext != null) { LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);//threadContextInheritable默认为false } if (requestAttributes != null) {//threadContextInheritable默认为false RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable); } }RequestContextHolder这个类有什么用呢?有时候我们想在某些类中获取HttpServletRequest对象,比如在AOP拦截的类中,那么我们就可以这样来获取Request的对象了,
HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);
DispatcherServlet#doService
@Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { //include这种的 Map<String, Object> attributesSnapshot = null; if (WebUtils.isIncludeRequest(request)) { attributesSnapshot = new HashMap<String, Object>(); Enumeration<?> attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) { attributesSnapshot.put(attrName, request.getAttribute(attrName)); } } } //Spring上下文 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 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); } } } }在这个方法中主要做了这几件事:处理include标签的请求,将上下文放到request的属性中,将国际化解析器放到request的属性中,将主题解析器放到request属性中,将主题放到request的属性中,处理重定向的请求数据最后调用doDispatch这个核心的方法对请求进行处理,我们在下一章中详细分析一下doDispatch这个方法。