面試官:你分析過SpringMVC的源碼嗎?
在研究源碼之前,先來回顧以下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>
值的註意的是contextConfigLocation和DispatcherServlet(用此類來攔截請求)的引用和配置。
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》中的一張圖來更好的了解執行過程:
``
上圖流程總體來說可分為三大塊:
Map的建立(並放入WebApplicationContext)
HttpRequest請求中Url的請求攔截處理(DispatchServlet處理)
反射調用Controller中對應的處理方法,並返回視圖
本文將圍繞這三塊進行分析。
- Map的建立
在容器初始化時會建立所有 url 和 Controller 的對應關系,保存到 Map<url,controller>中,那是如何保存的呢。// 初始化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的映射就裝配完成,下來就分析請求的處理過程。
- 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,它裏面就包含了我們在第一步完成的controller與url映射的信息。
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);
}
}
}
該方法主要是
通過request對象獲取到HandlerExecutionChain,HandlerExecutionChain對象裏面包含了攔截器interceptor和處理器handler。如果獲取到的對象是空,則交給noHandlerFound返回404頁面。
攔截器預處理,如果執行成功則進行3
獲取handler適配器 Adapter
實際的處理器處理並返回 ModelAndView 對象
下面是該方法中的一些核心細節:
DispatchServlet #doDispatch # noHandlerFound核心源碼:
1
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()方法實現.
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。
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的某個對應方法進行調用了。
看完後腦子一定很亂,有時間的話還是需要自己動手調試一下。本文只是串一下整體思路,所以功能性的源碼沒有全部分析。
其實理解這些才是最重要的。
用戶發送請求至前端控制器DispatcherServlet
DispatcherServlet收到請求調用HandlerMapping處理器映射器。
處理器映射器根據請求url找到具體的處理器,生成處理器對象及處理器攔截器(如果有則生成)一並返回給DispatcherServlet。
DispatcherServlet通過HandlerAdapter處理器適配器調用處理器
HandlerAdapter執行處理器(handler,也叫後端控制器)。
Controller執行完成返回ModelAndView
HandlerAdapter將handler執行結果ModelAndView返回給DispatcherServlet
DispatcherServlet將ModelAndView傳給ViewReslover視圖解析器
ViewReslover解析後返回具體View對象
DispatcherServlet對View進行渲染視圖(即將模型數據填充至視圖中)。
DispatcherServlet響應用戶
面試官:你分析過SpringMVC的源碼嗎?