SpringMVC源码解析从service到doDispatch

举报
JavaEdge 发表于 2021/06/04 01:02:46 2021/06/04
【摘要】 请求在被Servlet处理之前会先被过滤器处理,之后调用Servlet的service方法来对相应的请求进行处理响应。所以我们这里分析的入口是Servlet的service方法。 我们在用SpringMVC的时候,通常都会在web.xml中进行这样的配置: <servlet> <servlet-name>spring-mvc</ser...

请求在被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>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

所有的请求(除静态资源)将由DispatcherServlet处理。

DispatcherServlet继承了FrameworkServlet,FrameworkServlet继承了HttpServletBean,HttpServletBean继承了HttpServlet,HttpServlet继承了GenericServlet,GenericServlet则实现了我们最顶级的接口Servlet和ServletConfig。

	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.
		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(DEFAULT_STRATEGIES_PREFIX)) { attributesSnapshot.put(attrName, request.getAttribute(attrName)); } }
		} // Make framework objects available to handlers and view objects.
		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(request, response);
		}
		finally { if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) { // Restore the original attribute snapshot, in case of an include. if (attributesSnapshot != null) { restoreAttributesAfterInclude(request, attributesSnapshot); } }
		}
	}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

从DispatcherServlet的源码中我们没有找到service(ServletRequest req, ServletResponse res)这个方法,但是我们在DispatcherServlet的父类HttpServlet中找到了这个方法,我们去HttpServlet中看看这个方法的内容:

HttpServlet#service

将ServletRequest和ServletResponse转换为HttpServletRequest和HttpServletResponse

因为web开发,用HTTP协议,所以需要HttpServletRequest和HttpServletResponse

接下来就是调用service(HttpServletRequest request, HttpServletResponse response),

HttpServlet和FrameworkServlet中都找到了这个方法,但是HttpServlet是FrameworkServlet的父类,即FrameworkServlet中重写了service这个方法,所以我们这里取FrameworkServlet中去看看这个方法的内容:

FrameworkServlet#service


根据请求的方法类型转换对应的枚举类

HttpMethod这个定义了这样的几种枚举类型:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;而这些也是RFC标准中几种请求类型。如果请求类型为PATCH或者没有找到相应的请求类型的话,则直接调用processRequest这个方法。但是这种情况我们很少很少会遇到。
所以这里会执行super.service这个方法。即调用HttpServlet中的service方法。我们看一下HttpServlet中这个service方法的内容:

HttpServlet#service

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); }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

根据请求类型调用响应的请求方法如果GET类型,调用doGet方法
POST类型,调用doPost方法。
这些方法都是在HttpServlet中定义的,平时我们做web开发的时候主要是继承HttpServlet这个类,然后重写它的doPost或者doGet方法。
我们的FrameworkServlet这个子类就重写了这些方法中的一部分:doGet、doPost、doPut、doDelete、doOption、doTrace。

这里我们只说我们最常用的doGet和doPost这两个方法。通过翻开源码我们发现,这两个方法体的内容是一样的,都是调用了processRequest

FrameworkServlet#processRequest

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);
	}
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

国际化的设置,创建ServletRequestAttributes对象,初始化上下文holders(即将Request对象放入到线程上下文中),调用doService方法。

国际化的设置

DispatcherServlet#buildLocaleContext这个方法中完成的,其源码如下:

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); }
		};
	}
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

没有配置国际化解析器的话,那么它会使用默认的解析器: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);
	}
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

RequestContextHolder这个类有什么用呢?有时候我们想在某些类中获取HttpServletRequest对象,比如在AOP拦截的类中,那么我们就可以这样来获取Request的对象了,

HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);

  
 
  • 1

DispatcherServlet#doService

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
	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); }
		}
	}
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

处理include标签的请求,将上下文放到request的属性中,将国际化解析器放到request的属性中,将主题解析器放到request属性中,将主题放到request的属性中,处理重定向的请求数据最后调用doDispatch这个核心的方法对请求进行处理

后续流程

文章来源: javaedge.blog.csdn.net,作者:JavaEdge.,版权归原作者所有,如需转载,请联系作者。

原文链接:javaedge.blog.csdn.net/article/details/106566997

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200