spring源碼閱讀4,請求如何匹配

前文提要

根據前文
我們知道所有的http請求都會到
DispatcherServlet#doDispatch內,執(zhí)行下面兩個邏輯

  • 構造HandlerExecutionChain,根據請求的路徑找到HandlerMethod(帶有Method反射屬性,也就是對應Controller中的方法),然后匹配路徑對應的攔截器,有了HandlerMethod和攔截器構造個HandlerExecutionChain對象。HandlerExecutionChain對象的獲取是通過HandlerMapping接口提供的方法中得到。
  • 構造HandlerAdapter,有了HandlerExecutionChain之后,通過HandlerAdapter對象進行處理得到ModelAndView對象,HandlerMethod內部handle的時候,使用各種HandlerMethodArgumentResolver實現類處理HandlerMethod的參數,使用各種HandlerMethodReturnValueHandler實現類處理返回值。 最終返回值被處理成ModelAndView對象,這期間發(fā)生的異常會被HandlerExceptionResolver接口實現類進行處理

但是如何根據我們在Controller中定義的RequestMapping()來找到具體的處理方法呢? 本文主要介紹這個問題。

相關接口和實現

首先是RequestMappingInfo,它保存了匹配的各種條件,如Header條件,Pattern條件等根據名字其實也不難看出,它的繼承關系如下

image.png

org.springframework.web.servlet.mvc.condition.RequestCondition定義了一個接口,用于匹配請求

MappingRegistry用于保存所有的匹配信息,是AbstractHandlerMethodMapping的一個內部類
這個類設計上比較關鍵,受限于蝙蝠,這里先不展開

HandlerMethod類,用于存儲方法的相關信息

image.png

初始化RequestMappingHandlerMapping

開啟<mvc:annotation-driven/>,將會注冊兩個bean。RequestMappingHandlerMappingRequetMappingHandlerAdapter
用于分配請求
RequestMappingHandlerMapping的繼承關系如下

image.png

繼承了InitializingBean說明創(chuàng)建后會初始化,實現HandlerMapping可以獲取HandlerExecutionChain,繼承了ApplicationObjectSupport可以方便的獲取上下文對象
先看RequestMappingHandlerMapping初始化,調用了org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#initHandlerMethods,方法如下。

獲取所有的bean 找到所有被RequesMapping修飾的方法和類,調用detectHandlerMethods

protected void initHandlerMethods() {
if (logger.isDebugEnabled()) {
logger.debug("Looking for request mappings in application context: " + getApplicationContext());
}

//獲取所有的bean
String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));

for (String beanName : beanNames) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
Class<?> beanType = null;
//獲取bean的類型
try {
beanType = getApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
//isHandler 判斷類上是否有Controller或者RequestMapping注解
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
handlerMethodsInitialized(getHandlerMethods());
}

detectHandlerMethods 對被修飾的方法創(chuàng)建一個map用于存儲方法和具體匹配關系的映射,并且調用registerHandlerMethod把這些映射關系注冊到MappingRegistry的一個實例中,這個實例在org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#mappingRegistry

protected void detectHandlerMethods(final Object handler) {
Class<?> handlerType = (handler instanceof String ?
getApplicationContext().getType((String) handler) : handler.getClass());
final Class<?> userType = ClassUtils.getUserClass(handlerType);

//key是Method,值是一個泛型,在webmvc中是指org.springframework.web.servlet.mvc.method.RequestMappingInfo
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
new MethodIntrospector.MetadataLookup<T>() {
@Override
public T inspect(Method method) {
try {
//是抽象方法,具體由RequestMappingHandlerMapping實現
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
throw new IllegalStateException("Invalid mapping on handler class [" +
userType.getName() + "]: " + method, ex);
}
}
});

if (logger.isDebugEnabled()) {
logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
}
for (Map.Entry<Method, T> entry : methods.entrySet()) {
Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);
T mapping = entry.getValue();
registerHandlerMethod(handler, invocableMethod, mapping);
}
}

getMappingForMethod中定義了如何根據一個RequestMapping方法得到一個存儲匹配信息的RequestMappingInfo,這里類的設計的比較巧妙,受限于篇幅,先按住不表。

從http請求到HandlerExecutionChain

回憶下我們說DispatcherServlet初始化的部分,DispatcherServlet最后的步驟是經由onRefresh調用initStrategies,其中initHandlerMappings用于初始化HandleMapping

private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;

if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}

// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}

如果是需要找到所有HandleMapping的子類開啟,則在所有bean定義中找到所有HandleMapping的實現,并且作為元素放入org.springframework.web.servlet.DispatcherServlet#handlerMappings
否則將從bean中找到名字為handlerMapping作為唯一HandleMapping

一般情況下 需要找到所有HandleMapping的子類開啟

調用org.springframework.web.servlet.DispatcherServlet#getHandler獲取具體的handler

protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
HandlerExecutionChain handler = hm.getHandler(request);
if (handler != null) {
return handler;
}
}
return null;
}

也就是說通常情況下,getHandler最終會調用org.springframework.web.servlet.handler.RequestMappingHandlerMapping#getHandler
這個方法定義在其父類AbstractHandlerMapping中,這個方法分主要內容是獲取通過getHandlerInternal獲取handler并且組成HandlerExecutionChain

public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}

HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.globalCorsConfigSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}

getHandlerInternal是實際獲取的handler,定義在AbstractHandlerMethodMapping,獲取讀取鎖后調用lookupHandlerMethod查找handler后釋放鎖

@Override
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
if (logger.isDebugEnabled()) {
logger.debug("Looking up handler method for path " + lookupPath);
}
this.mappingRegistry.acquireReadLock();
try {
HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
if (logger.isDebugEnabled()) {
if (handlerMethod != null) {
logger.debug("Returning handler method [" + handlerMethod + "]");
}
else {
logger.debug("Did not find handler method for [" + lookupPath + "]");
}
}
return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
}
finally {
this.mappingRegistry.releaseReadLock();
}
}

看看核心匹配方法lookupHandlerMethod

protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<Match>();
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
// No choice but to go through all mappings...
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}

if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
Collections.sort(matches, comparator);
if (logger.isTraceEnabled()) {
logger.trace("Found " + matches.size() + " matching mapping(s) for [" +
lookupPath + "] : " + matches);
}
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (CorsUtils.isPreFlightRequest(request)) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" +
request.getRequestURL() + "': {" + m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
}
}

返回最佳匹配,修飾的方法就找到了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容