前文提要
根據(jù)前文
我們知道所有的http請求都會到
DispatcherServlet#doDispatch
內(nèi)霹俺,執(zhí)行下面兩個邏輯
- 構(gòu)造
HandlerExecutionChain
,根據(jù)請求的路徑找到HandlerMethod(帶有Method反射屬性毒费,也就是對應Controller中的方法)丙唧,然后匹配路徑對應的攔截器,有了HandlerMethod和攔截器構(gòu)造個HandlerExecutionChain對象觅玻。HandlerExecutionChain對象的獲取是通過HandlerMapping接口提供的方法中得到想际。 - 構(gòu)造HandlerAdapter,有了HandlerExecutionChain之后,通過HandlerAdapter對象進行處理得到ModelAndView對象溪厘,HandlerMethod內(nèi)部handle的時候沼琉,使用各種HandlerMethodArgumentResolver實現(xiàn)類處理HandlerMethod的參數(shù),使用各種HandlerMethodReturnValueHandler實現(xiàn)類處理返回值桩匪。 最終返回值被處理成ModelAndView對象打瘪,這期間發(fā)生的異常會被HandlerExceptionResolver接口實現(xiàn)類進行處理
但是如何根據(jù)我們在Controller中定義的RequestMapping()來找到具體的處理方法呢? 本文主要介紹這個問題傻昙。
相關接口和實現(xiàn)
首先是RequestMappingInfo
闺骚,它保存了匹配的各種條件,如Header條件妆档,Pattern條件等根據(jù)名字其實也不難看出僻爽,它的繼承關系如下
org.springframework.web.servlet.mvc.condition.RequestCondition
定義了一個接口,用于匹配請求
MappingRegistry
用于保存所有的匹配信息贾惦,是AbstractHandlerMethodMapping
的一個內(nèi)部類
這個類設計上比較關鍵胸梆,受限于蝙蝠,這里先不展開
HandlerMethod
類须板,用于存儲方法的相關信息
初始化RequestMappingHandlerMapping
開啟<mvc:annotation-driven/>,
將會注冊兩個bean碰镜。RequestMappingHandlerMapping
和RequetMappingHandlerAdapter
用于分配請求
RequestMappingHandlerMapping
的繼承關系如下
繼承了
InitializingBean
說明創(chuàng)建后會初始化,實現(xiàn)HandlerMapping
可以獲取HandlerExecutionChain
习瑰,繼承了ApplicationObjectSupport
可以方便的獲取上下文對象先看
RequestMappingHandlerMapping
初始化绪颖,調(diào)用了org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#initHandlerMethods
,方法如下甜奄。
獲取所有的bean 找到所有被RequesMapping修飾的方法和類柠横,調(diào)用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用于存儲方法和具體匹配關系的映射窃款,并且調(diào)用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實現(xiàn)
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
中定義了如何根據(jù)一個RequestMapping方法
得到一個存儲匹配信息的RequestMappingInfo
搬俊,這里類的設計的比較巧妙紊扬,受限于篇幅,先按住不表悠抹。
從http請求到HandlerExecutionChain
回憶下我們說DispatcherServlet
初始化的部分,DispatcherServlet最后的步驟是經(jīng)由onRefresh
調(diào)用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的實現(xiàn)
,并且作為元素放入org.springframework.web.servlet.DispatcherServlet#handlerMappings
中
否則將從bean中找到名字為handlerMapping
作為唯一HandleMapping
一般情況下 需要找到所有HandleMapping的子類開啟
調(diào)用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
最終會調(diào)用org.springframework.web.servlet.handler.RequestMappingHandlerMapping#getHandler
這個方法定義在其父類AbstractHandlerMapping中卵凑,這個方法分主要內(nèi)容是獲取通過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
胜臊,獲取讀取鎖后調(diào)用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);
}
}
返回最佳匹配勺卢,修飾的方法就找到了