從SpringMvc原始碼分析其工作原理

微笑面對生活發表於2019-04-18

1. MVC使用

在研究原始碼之前,先來回顧以下springmvc 是如何配置的,這將能使我們更容易理解原始碼。

1.1 web.xml

<servlet>
	<servlet-name>mvc-dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<!-- 配置springMVC需要載入的配置檔案
		spring-dao.xml,spring-service.xml,spring-web.xml
		Mybatis - > spring -> springmvc
	 -->
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/spring-*.xml</param-value>
	</init-param>
</servlet>
<servlet-mapping>
	<servlet-name>mvc-dispatcher</servlet-name>
	<!-- 預設匹配所有的請求 -->
	<url-pattern>/</url-pattern>
</servlet-mapping>
複製程式碼

值的注意的是contextConfigLocationDispatcherServlet(用此類來攔截請求)的引用和配置。

1.2 spring-web.xml

<!-- 配置SpringMVC -->
<!-- 1.開啟SpringMVC註解模式 -->
<!-- 簡化配置: 
	(1)自動註冊DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 
	(2)提供一些列:資料繫結,數字和日期的format @NumberFormat, @DateTimeFormat, xml,json預設讀寫支援 
-->
<mvc:annotation-driven />

<!-- 2.靜態資源預設servlet配置
	(1)加入對靜態資源的處理:js,gif,png
	(2)允許使用"/"做整體對映
 -->
 <mvc:default-servlet-handler/>
 
 <!-- 3.配置jsp 顯示ViewResolver -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 	<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
 	<property name="prefix" value="/WEB-INF/jsp/" />
 	<property name="suffix" value=".jsp" />
 </bean>
 
 <!-- 4.掃描web相關的bean -->
 <context:component-scan base-package="com.xxx.fantj.web" />
複製程式碼

值的注意的是InternalResourceViewResolver,它會在ModelAndView返回的試圖名前面加上prefix字首,在後面載入suffix指定字尾。

SpringMvc主支原始碼分析

引用《Spring in Action》中的一張圖來更好的瞭解執行過程:

從SpringMvc原始碼分析其工作原理

上圖流程總體來說可分為三大塊:

  1. Map<url,Controller>的建立(並放入WebApplicationContext)
  2. HttpRequest請求中Url的請求攔截處理(DispatchServlet處理)
  3. 反射呼叫Controller中對應的處理方法,並返回檢視

本文將圍繞這三塊進行分析。

1. Map的建立

在容器初始化時會建立所有 url 和 Controller 的對應關係,儲存到 Map<url,Controller>中,那是如何儲存的呢。

ApplicationObjectSupport #setApplicationContext方法
// 初始化ApplicationContext
@Override
public void initApplicationContext() throws ApplicationContextException {
	super.initApplicationContext();
	detectHandlers();
}
複製程式碼
AbstractDetectingUrlHandlerMapping #detectHandlers()方法:
/**
 * 建立當前ApplicationContext 中的 所有Controller 和url 的對應關係
 * Register all handlers found in the current ApplicationContext.
 * <p>The actual URL determination for a handler is up to the concrete
 * {@link #determineUrlsForHandler(String)} implementation. A bean for
 * which no such URLs could be determined is simply not considered a handler.
 * @throws org.springframework.beans.BeansException if the handler couldn't be registered
 * @see #determineUrlsForHandler(String)
 */
protected void detectHandlers() throws BeansException {
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for URL mappings in application context: " + getApplicationContext());
	}
	// 獲取容器中的beanNames
	String[] beanNames = (this.detectHandlersInAncestorContexts ?
			BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
			getApplicationContext().getBeanNamesForType(Object.class));
	// 遍歷 beanNames 並找到對應的 url
	// Take any bean name that we can determine URLs for.
	for (String beanName : beanNames) {
		// 獲取bean上的url(class上的url + method 上的 url)
		String[] urls = determineUrlsForHandler(beanName);
		if (!ObjectUtils.isEmpty(urls)) {
			// URL paths found: Let's consider it a handler.
			// 儲存url 和 beanName 的對應關係
			registerHandler(urls, beanName);
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Rejected bean name '" + beanName + "': no URL paths identified");
			}
		}
	}
}
複製程式碼
determineUrlsForHandler()方法:

該方法在不同的子類有不同的實現,我這裡分析的是DefaultAnnotationHandlerMapping類的實現,該類主要負責處理@RequestMapping註解形式的宣告。

/**
 * 獲取@RequestMaping註解中的url
 * Checks for presence of the {@link org.springframework.web.bind.annotation.RequestMapping}
 * annotation on the handler class and on any of its methods.
 */
@Override
protected String[] determineUrlsForHandler(String beanName) {
	ApplicationContext context = getApplicationContext();
	Class<?> handlerType = context.getType(beanName);
	// 獲取beanName 上的requestMapping
	RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class);
	if (mapping != null) {
        // 類上面有@RequestMapping 註解
		this.cachedMappings.put(handlerType, mapping);
		Set<String> urls = new LinkedHashSet<String>();
		// mapping.value()就是獲取@RequestMapping註解的value值
		String[] typeLevelPatterns = mapping.value();
		if (typeLevelPatterns.length > 0) {
            // 獲取Controller 方法上的@RequestMapping
			String[] methodLevelPatterns = determineUrlsForHandlerMethods(handlerType);
			for (String typeLevelPattern : typeLevelPatterns) {
				if (!typeLevelPattern.startsWith("/")) {
					typeLevelPattern = "/" + typeLevelPattern;
				}
				for (String methodLevelPattern : methodLevelPatterns) {
					// controller的對映url+方法對映的url
					String combinedPattern = getPathMatcher().combine(typeLevelPattern, methodLevelPattern);
					// 儲存到set集合中
					addUrlsForPath(urls, combinedPattern);
				}
				addUrlsForPath(urls, typeLevelPattern);
			}
			// 以陣列形式返回controller上的所有url
			return StringUtils.toStringArray(urls);
		}
		else {
			// controller上的@RequestMapping對映url為空串,直接找方法的對映url
			return determineUrlsForHandlerMethods(handlerType);
		}
	}
	// controller上沒@RequestMapping註解
	else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) {
		// 獲取controller中方法上的對映url
		return determineUrlsForHandlerMethods(handlerType);
	}
	else {
		return null;
	}
}
複製程式碼

更深的細節程式碼就比較簡單了,有興趣的可以繼續深入。

到這裡,Controller和Url的對映就裝配完成,下來就分析請求的處理過程。

2. url的請求處理

我們在xml中配置了DispatcherServlet為排程器,所以我們就來看它的程式碼,可以 從名字上看出它是個Servlet,那麼它的核心方法就是doService()

DispatcherServlet #doService():
/**
 * 將DispatcherServlet特定的請求屬性和委託 公開給{@link #doDispatch}以進行實際排程。
 * Exposes the DispatcherServlet-specific request attributes and delegates to {@link #doDispatch}
 * for the actual dispatching.
 */
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
	if (logger.isDebugEnabled()) {
		String requestUri = new UrlPathHelper().getRequestUri(request);
		logger.debug("DispatcherServlet with name '" + getServletName() + "' processing " + request.getMethod() +
				" request for [" + requestUri + "]");
	}

    //在包含request的情況下保留請求屬性的快照,
    //能夠在include之後恢復原始屬性。
	Map<String, Object> attributesSnapshot = null;
	if (WebUtils.isIncludeRequest(request)) {
		logger.debug("Taking snapshot of request attributes before include");
		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));
			}
		}
	}

	// 使得request物件能供 handler處理和view處理 使用
	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());

	try {
		doDispatch(request, response);
	}
	finally {
		// 如果不為空,則還原原始屬性快照。
		if (attributesSnapshot != null) {
			restoreAttributesAfterInclude(request, attributesSnapshot);
		}
	}
}

複製程式碼

可以看到,它將請求拿到後,主要是給request設定了一些物件,以便於後續工作的處理(Handler處理和view處理)。比如WebApplicationContext,它裡面就包含了我們在第一步完成的controllerurl對映的資訊。

DispatchServlet # doDispatch()
/**
 * 控制請求轉發
 * 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 {
	HttpServletRequest processedRequest = request;
	HandlerExecutionChain mappedHandler = null;
	int interceptorIndex = -1;

	try {

		ModelAndView mv;
		boolean errorView = false;

		try {
		    // 1. 檢查是否是上傳檔案
			processedRequest = checkMultipart(request);

			// Determine handler for the current request.
            // 2. 獲取handler處理器,返回的mappedHandler封裝了handlers和interceptors
			mappedHandler = getHandler(processedRequest, false);
			if (mappedHandler == null || mappedHandler.getHandler() == null) {
			    // 返回404
				noHandlerFound(processedRequest, response);
				return;
			}

			// Apply preHandle methods of registered interceptors.
            // 獲取HandlerInterceptor的預處理方法
			HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
			if (interceptors != null) {
				for (int i = 0; i < interceptors.length; i++) {
					HandlerInterceptor interceptor = interceptors[i];
					if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
						triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
						return;
					}
					interceptorIndex = i;
				}
			}

			// Actually invoke the handler.
            // 3. 獲取handler介面卡 Adapter
			HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
			// 4. 實際的處理器處理並返回 ModelAndView 物件
			mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

			// Do we need view name translation?
			if (mv != null && !mv.hasView()) {
				mv.setViewName(getDefaultViewName(request));
			}

			// HandlerInterceptor 後處理
			if (interceptors != null) {
				for (int i = interceptors.length - 1; i >= 0; i--) {
					HandlerInterceptor interceptor = interceptors[i];
					// 結束檢視物件處理
					interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);
				}
			}
		}
		catch (ModelAndViewDefiningException ex) {
			logger.debug("ModelAndViewDefiningException encountered", ex);
			mv = ex.getModelAndView();
		}
		catch (Exception ex) {
			Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
			mv = processHandlerException(processedRequest, response, handler, ex);
			errorView = (mv != null);
		}

		// Did the handler return a view to render?
		if (mv != null && !mv.wasCleared()) {
			render(mv, processedRequest, response);
			if (errorView) {
				WebUtils.clearErrorRequestAttributes(request);
			}
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() +
						"': assuming HandlerAdapter completed request handling");
			}
		}

		// Trigger after-completion for successful outcome.
		// 請求成功響應之後的方法
		triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
	}

	catch (Exception ex) {
		// Trigger after-completion for thrown exception.
		triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
		throw ex;
	}
	catch (Error err) {
		ServletException ex = new NestedServletException("Handler processing failed", err);
		// Trigger after-completion for thrown exception.
		triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
		throw ex;
	}

	finally {
		// Clean up any resources used by a multipart request.
		if (processedRequest != request) {
			cleanupMultipart(processedRequest);
		}
	}
}
複製程式碼

該方法主要是

  1. 通過request物件獲取到HandlerExecutionChainHandlerExecutionChain物件裡面包含了攔截器interceptor和處理器handler。如果獲取到的物件是空,則交給noHandlerFound返回404頁面。
  2. 攔截器預處理,如果執行成功則進行3
  3. 獲取handler介面卡 Adapter
  4. 實際的處理器處理並返回 ModelAndView 物件

下面是該方法中的一些核心細節:

DispatchServlet #doDispatch # noHandlerFound核心原始碼:

response.sendError(HttpServletResponse.SC_NOT_FOUND);
複製程式碼

DispatchServlet #doDispatch #getHandler方法事實上呼叫的是AbstractHandlerMapping #getHandler方法,我貼出一個核心的程式碼:

// 拿到處理物件
Object handler = getHandlerInternal(request);
...
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
...
// 返回HandlerExecutionChain物件
return getHandlerExecutionChain(handler, request);
複製程式碼

可以看到,它先從request裡獲取handler物件,這就證明了之前DispatchServlet #doService為什麼要吧WebApplicationContext放入request請求物件中。

最終返回一個HandlerExecutionChain物件.

3. 反射呼叫處理請求的方法,返回結果檢視

在上面的原始碼中,實際的處理器處理並返回 ModelAndView 物件呼叫的是mv = ha.handle(processedRequest, response, mappedHandler.getHandler());這個方法。該方法由AnnotationMethodHandlerAdapter #handle() #invokeHandlerMethod()方法實現.

AnnotationMethodHandlerAdapter #handle() #invokeHandlerMethod()
/**
 * 獲取處理請求的方法,執行並返回結果檢視
 */
protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {

    // 1.獲取方法解析器
	ServletHandlerMethodResolver methodResolver = getMethodResolver(handler);
	// 2.解析request中的url,獲取處理request的方法
	Method handlerMethod = methodResolver.resolveHandlerMethod(request);
	// 3. 方法呼叫器
	ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver);
	ServletWebRequest webRequest = new ServletWebRequest(request, response);
	ExtendedModelMap implicitModel = new BindingAwareModelMap();
	// 4.執行方法(獲取方法的引數)
	Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);
	// 5. 封裝成mv檢視
	ModelAndView mav =
			methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest);
	methodInvoker.updateModelAttributes(handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);
	return mav;
}
複製程式碼

這個方法有兩個重要的地方,分別是resolveHandlerMethodinvokeHandlerMethod

resolveHandlerMethod 方法

methodResolver.resolveHandlerMethod(request):獲取controller類和方法上的@requestMapping value,與request的url進行匹配,找到處理request的controller中的方法.最終拼接的具體實現是org.springframework.util.AntPathMatcher#combine方法。

invokeHandlerMethod方法

從名字就能看出來它是基於反射,那它做了什麼呢。

解析該方法上的引數,並呼叫該方法。

//上面全都是為解析方法上的引數做準備
...
// 解析該方法上的引數
Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);
// 真正執行解析呼叫的方法
return doInvokeMethod(handlerMethodToInvoke, handler, args);
複製程式碼
invokeHandlerMethod方法#resolveHandlerArguments方法

程式碼有點長,我就簡介下它做了什麼事情吧。

  • 如果這個方法的引數用的是註解,則解析註解拿到引數名,然後拿到request中的引數名,兩者一致則進行賦值(詳細程式碼在HandlerMethodInvoker#resolveRequestParam),然後將封裝好的物件放到args[]的陣列中並返回。
  • 如果這個方法的引數用的不是註解,則需要asm框架(底層是讀取位元組碼)來幫助獲取到引數名,然後拿到request中的引數名,兩者一致則進行賦值,然後將封裝好的物件放到args[]的陣列中並返回。
invokeHandlerMethod方法#doInvokeMethod方法
private Object doInvokeMethod(Method method, Object target, Object[] args) throws Exception {
	// 將一個方法設定為可呼叫,主要針對private方法
	ReflectionUtils.makeAccessible(method);
	try {
		// 反射呼叫
		return method.invoke(target, args);
	}
	catch (InvocationTargetException ex) {
		ReflectionUtils.rethrowException(ex.getTargetException());
	}
	throw new IllegalStateException("Should never get here");
}
複製程式碼

到這裡,就可以對request請求中url對應的controller的某個對應方法進行呼叫了。

總結:

看完後腦子一定很亂,有時間的話還是需要自己動手除錯一下。本文只是串一下整體思路,所以功能性的原始碼沒有全部分析。

其實理解這些才是最重要的。

  1. 使用者傳送請求至前端控制器DispatcherServlet
  2. DispatcherServlet收到請求呼叫HandlerMapping處理器對映器。
  3. 處理器對映器根據請求url找到具體的處理器,生成處理器物件及處理器攔截器(如果有則生成)一併返回給DispatcherServlet。
  4. DispatcherServlet通過HandlerAdapter處理器介面卡呼叫處理器
  5. HandlerAdapter執行處理器(handler,也叫後端控制器)。
  6. Controller執行完成返回ModelAndView
  7. HandlerAdapter將handler執行結果ModelAndView返回給DispatcherServlet
  8. DispatcherServlet將ModelAndView傳給ViewReslover檢視解析器
  9. ViewReslover解析後返回具體View物件
  10. DispatcherServlet對View進行渲染檢視(即將模型資料填充至檢視中)。
  11. DispatcherServlet響應使用者

參考文獻:

最後,分享一波福利

從SpringMvc原始碼分析其工作原理
點選進入:我的Java學習歷程與面試知識總結

相關文章