在研究源碼以前,先來回顧如下springmvc 是如何配置的,這將能使咱們更容易理解源碼。前端
<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>
複製代碼
值的注意的是contextConfigLocation
和DispatcherServlet
(用此類來攔截請求)的引用和配置。web
<!-- 配置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
指定後綴。面試
引用《Spring in Action》中的一張圖來更好的瞭解執行過程: spring
上圖流程整體來講可分爲三大塊:json
Map
的創建(並放入WebApplicationContext
)後端
HttpRequest
請求中Url的請求攔截處理(DispatchServlet處理)api
反射調用Controller
中對應的處理方法,並返回視圖數組
本文將圍繞這三塊進行分析。bash
在容器初始化時會創建全部 url 和 Controller 的對應關係,保存到 Map中,那是如何保存的呢。架構
// 初始化ApplicationContext
@Override
public void initApplicationContext() throws ApplicationContextException {
super.initApplicationContext();
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");
}
}
}
}
複製代碼
該方法在不一樣的子類有不一樣的實現,我這裏分析的是
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的映射就裝配完成,下來就分析請求的處理過程。
咱們在xml中配置了
DispatcherServlet
爲調度器,因此咱們就來看它的代碼,能夠
從名字上看出它是個Servlet
,那麼它的核心方法就是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
,它裏面就包含了咱們在第一步完成的controller
與url
映射的信息。
/**
* 控制請求轉發
* 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); } } } 複製代碼
該方法主要是
經過request對象獲取到HandlerExecutionChain
,HandlerExecutionChain
對象裏面包含了攔截器interceptor和處理器handler。若是獲取到的對象是空,則交給noHandlerFound
返回404頁面。
攔截器預處理,若是執行成功則進行3
獲取handler適配器 Adapter
實際的處理器處理並返回 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
對象.
在上面的源碼中,實際的處理器處理並返回 ModelAndView 對象調用的是
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
這個方法。該方法由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;
}
複製代碼
這個方法有兩個重要的地方,分別是resolveHandlerMethod
和invokeHandlerMethod
。
methodResolver.resolveHandlerMethod(request)
:獲取controller類和方法上的@requestMapping value
,與request的url進行匹配,找處處理request的controller中的方法.最終拼接的具體實現是org.springframework.util.AntPathMatcher#combine
方法。
從名字就能看出來它是基於反射,那它作了什麼呢。
解析該方法上的參數,並調用該方法。
//上面全都是爲解析方法上的參數作準備
...
// 解析該方法上的參數
Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);
// 真正執行解析調用的方法
return doInvokeMethod(handlerMethodToInvoke, handler, args);
複製代碼
代碼有點長,我就簡介下它作了什麼事情吧。
若是這個方法的參數用的是註解,則解析註解拿到參數名,而後拿到request中的參數名,二者一致則進行賦值(詳細代碼在HandlerMethodInvoker#resolveRequestParam
),而後將封裝好的對象放到args[]的數組中並返回。
若是這個方法的參數用的不是註解,則須要asm框架(底層是讀取字節碼)來幫助獲取到參數名,而後拿到request中的參數名,二者一致則進行賦值,而後將封裝好的對象放到args[]的數組中並返回。
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的某個對應方法進行調用了。
看完後腦子必定很亂,有時間的話仍是須要本身動手調試一下。本文只是串一下總體思路,因此功能性的源碼沒有所有分析。
其實理解這些纔是最重要的。
用戶發送請求至前端控制器DispatcherServlet
DispatcherServlet收到請求調用HandlerMapping處理器映射器。
處理器映射器根據請求url找到具體的處理器,生成處理器對象及處理器攔截器(若是有則生成)一併返回給DispatcherServlet。
DispatcherServlet經過HandlerAdapter處理器適配器調用處理器
HandlerAdapter執行處理器(handler,也叫後端控制器)。
Controller執行完成返回ModelAndView
HandlerAdapter將handler執行結果ModelAndView返回給DispatcherServlet
DispatcherServlet將ModelAndView傳給ViewReslover視圖解析器
ViewReslover解析後返回具體View對象
DispatcherServlet對View進行渲染視圖(即將模型數據填充至視圖中)。
DispatcherServlet響應用戶
文章來源:公衆號
歡迎工做一到五年的Java工程師朋友們加入Java高級互聯網架構羣:643459718 免費領取架構師資料