之前分析過SpringMVC中的DispatcherServlet,分析了SpringMVC處理請(qǐng)求的過程。但忽略了一些DispatcherServlet協(xié)助請(qǐng)求處理的組件,例如SpringMVC中的HandlerMapping、HandlerAdapter、ViewResolvers等等。
HandlerMappings
HandlerMappings在DispathServlet中主要作用是為請(qǐng)求的urlpath匹配對(duì)應(yīng)的Controller,建立一個(gè)映射關(guān)系,根據(jù)請(qǐng)求查找Handler、Interceptor。HandlerMappings將請(qǐng)求傳遞到HandlerExecutionChain上,HandlerExecutionChain包含了一個(gè)能夠處理該請(qǐng)求的處理器,還可以包含攔截改請(qǐng)求的攔截器。
在沒有處理器映射相關(guān)配置情況下,DispatcherServlet會(huì)為你創(chuàng)建一個(gè)BeanNameUrlHandlerMapping作為默認(rèn)映射的配置。在DispatchServlet.properties文件中對(duì)于HandlerMapping的默認(rèn)配置是:
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
HandlerMapping的配置策略一般分為配置式BeanNameUrlHandlerMapping和注解式DefaultAnnotationHandlerMapping。不過DefaultAnnotationHandlerMapping已經(jīng)被放棄了,取代它的是RequestMappingHandlerMapping,不知道為啥SpringMVC這個(gè)默認(rèn)配置尚未做修改。
AbstractHandlerMapping

AbstractHandlerMapping是HandlerMapping的抽象實(shí)現(xiàn),是所有HandlerMapping實(shí)現(xiàn)類的父類。
AbstractHandlerMapping的作用是是為了初始化Interceptors。AbstractHandlerMapping重寫了WebApplicationObjectSupport的initApplicationContext方法。
protected void initApplicationContext() throws BeansException {
extendInterceptors(this.interceptors);
detectMappedInterceptors(this.adaptedInterceptors);
initInterceptors();
}
extendInterceptors方法,Springmvc并沒有做出具體實(shí)現(xiàn),這里留下一個(gè)拓展,子類可以重寫這個(gè)模板方法,為子類添加或者修改Interceptors。detectMappedInterceptors方法將SpringMVC容器中所有MappedInterceptor類的bean添加到adaptedInterceptors中。最后調(diào)用
initInterceptors初始化攔截器。遍歷interceptors將WebRequestInterceptor和HandlerInterceptor類型的攔截器添加到adaptedInterceptors中。
HandlerMapping通過getHandler方法來獲取請(qǐng)求的處理器Handler和攔截器Interceptor。在getHandlerExecutionChain方法中將遍歷之前初始化的adaptedInterceptors,為當(dāng)前的請(qǐng)求選擇對(duì)應(yīng)的MappedInterceptors和adaptedInterceptors。
AbstractUrlHandlerMapping
AbstractUrlHandlerMapping

AbstractUrlHandlerMapping繼承于AbstractHandlerMapping,它是通過URL來匹配具體的Handler。AbstractUrlHandlerMapping維護(hù)一個(gè)handlerMap來存儲(chǔ)Url和Handler的映射關(guān)系。
AbstractUrlHandlerMapping重寫了AbstractHandlerMapping類中的getHandlerInternal方法。HandlerMapping通過getHandler方法,就會(huì)調(diào)用這里的getHandlerInternal方法來獲取Handler。getHandlerInternal方法中關(guān)鍵調(diào)用lookupHandler方法去獲取handler。
protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {
// Direct match?
Object handler = this.handlerMap.get(urlPath);
if (handler != null) {
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
return buildPathExposingHandler(handler, urlPath, urlPath, null);
}
// Pattern match?
List<String> matchingPatterns = new ArrayList<String>();
for (String registeredPattern : this.handlerMap.keySet()) {
if (getPathMatcher().match(registeredPattern, urlPath)) {
matchingPatterns.add(registeredPattern);
}
else if (useTrailingSlashMatch()) {
if (!registeredPattern.endsWith("/") && getPathMatcher().match(registeredPattern + "/", urlPath)) {
matchingPatterns.add(registeredPattern +"/");
}
}
}
String bestMatch = null;
Comparator<String> patternComparator = getPathMatcher().getPatternComparator(urlPath);
if (!matchingPatterns.isEmpty()) {
Collections.sort(matchingPatterns, patternComparator);
if (logger.isDebugEnabled()) {
logger.debug("Matching patterns for request [" + urlPath + "] are " + matchingPatterns);
}
bestMatch = matchingPatterns.get(0);
}
if (bestMatch != null) {
handler = this.handlerMap.get(bestMatch);
if (handler == null) {
if (bestMatch.endsWith("/")) {
handler = this.handlerMap.get(bestMatch.substring(0, bestMatch.length() - 1));
}
if (handler == null) {
throw new IllegalStateException(
"Could not find handler for best pattern match [" + bestMatch + "]");
}
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestMatch, urlPath);
// There might be multiple 'best patterns', let's make sure we have the correct URI template variables
// for all of them
Map<String, String> uriTemplateVariables = new LinkedHashMap<String, String>();
for (String matchingPattern : matchingPatterns) {
if (patternComparator.compare(bestMatch, matchingPattern) == 0) {
Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(matchingPattern, urlPath);
Map<String, String> decodedVars = getUrlPathHelper().decodePathVariables(request, vars);
uriTemplateVariables.putAll(decodedVars);
}
}
if (logger.isDebugEnabled()) {
logger.debug("URI Template variables for request [" + urlPath + "] are " + uriTemplateVariables);
}
return buildPathExposingHandler(handler, bestMatch, pathWithinMapping, uriTemplateVariables);
}
// No handler found...
return null;
}
- 首先調(diào)用
lookupHandler方法來獲取handler。在lookupHandler方法中,先通過URL在handlerMap查找是否有合適的handler。 - 如果沒有獲取到
handler,遍歷handlerMap利用正則匹配的方法,找到符合要求的handlers(有可能是多個(gè))。 - 正則匹配是采用
Ant風(fēng)格,將會(huì)通過排序篩選出一個(gè)匹配程度最高的Handler。 - 最后調(diào)用
buildPathExposingHandler方法構(gòu)建一個(gè)handler,添加PathExposingHandlerInterceptor和UriTemplateVariablesHandlerInterceptor兩個(gè)攔截器并返回。
上面介紹獲取handler的過程中,會(huì)先從handlerMap查找。下面看一下handlerMap是如何初始化的。AbstractUrlHandlerMapping是通過registerHandler初始化handlerMap的。AbstractUrlHandlerMapping共有兩個(gè)registerHandler方法。分別是注冊(cè)多個(gè)url到一個(gè)handler和注冊(cè)一個(gè)url到一個(gè)handler。首先判斷handlerMap是否有此handler。如果存在的話,判斷是否一致,不一致則拋出異常,如果不存在的話,如果url是/、/*,則,返回root handler、default handler,如果不是將添加到handlerMap中。
SimpleUrlHandlerMapping

SimpleUrlHandlerMapping繼承于AbstractUrlHandlerMapping。SimpleUrlHandlerMapping重寫了父類AbstractHandlerMapping中的初始化方法initApplicationContext。在initApplicationContext方法中調(diào)用registerHandlers方法。
protected void registerHandlers(Map<String, Object> urlMap) throws BeansException {
if (urlMap.isEmpty()) {
logger.warn("Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping");
}
else {
for (Map.Entry<String, Object> entry : urlMap.entrySet()) {
String url = entry.getKey();
Object handler = entry.getValue();
// Prepend with slash if not already present.
if (!url.startsWith("/")) {
url = "/" + url;
}
// Remove whitespace from handler bean name.
if (handler instanceof String) {
handler = ((String) handler).trim();
}
registerHandler(url, handler);
}
}
}
判斷是url是否以/開頭,如果不是,默認(rèn)補(bǔ)齊/,確保所有的url都是以/開頭,然后依次調(diào)用父類的registerHandler方法注冊(cè)到AbstractUrlHandlerMapping中的handlerMap。
在使用SimpleUrlHandlerMapping時(shí),需要在注冊(cè)的時(shí)候配置其urlmap否則會(huì)拋異常。
AbstractDetectingUrlHandlerMapping

AbstractDetectingUrlHandlerMapping類繼承于AbstractUrlHandlerMapping類,重寫了initApplicationContext方法,在initApplicationContext方法中調(diào)用了detectHandlers方法。
protected void detectHandlers() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Looking for URL mappings in application context: " + getApplicationContext());
}
String[] beanNames = (this.detectHandlersInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));
// Take any bean name that we can determine URLs for.
for (String beanName : beanNames) {
String[] urls = determineUrlsForHandler(beanName);
if (!ObjectUtils.isEmpty(urls)) {
// URL paths found: Let's consider it a handler.
registerHandler(urls, beanName);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Rejected bean name '" + beanName + "': no URL paths identified");
}
}
}
}
獲取所有容器的beanNames,遍歷所有的beanName,調(diào)用determineUrlsForHandler方法解析url,這里的determineUrlsForHandler也是運(yùn)用了模板方法設(shè)計(jì)模式,具體的實(shí)現(xiàn)在其子類中,如果解析到子類,將注冊(cè)到父類的handlerMap中。
BeanNameUrlHandlerMapping
BeanNameUrlHandlerMapping類的類圖大致如下:

BeanNameUrlHandlerMapping類繼承于AbstractDetectingUrlHandlerMapping類。重寫了父類中的determineUrlsForHandler方法。
protected String[] determineUrlsForHandler(String beanName) {
List<String> urls = new ArrayList<String>();
if (beanName.startsWith("/")) {
urls.add(beanName);
}
String[] aliases = getApplicationContext().getAliases(beanName);
for (String alias : aliases) {
if (alias.startsWith("/")) {
urls.add(alias);
}
}
return StringUtils.toStringArray(urls);
}
其通過beanName解析Url規(guī)則也很簡(jiǎn)單,判斷beanName是否以/開頭。
BeanNameUrlHandlerMapping是SpringMVC的默認(rèn)映射配置。
AbstractHandlerMethodMapping
通常我們也習(xí)慣于用@Controller、@Re questMapping來定義Handler,AbstractHandlerMethodMapping可以將method作為Handler來使用。
AbstractHandlerMethodMapping實(shí)現(xiàn)了InitializingBean接口,實(shí)現(xiàn)了afterPropertiesSet方法。當(dāng)容器啟動(dòng)的時(shí)候會(huì)調(diào)用initHandlerMethods注冊(cè)委托handler中的方法。
public void afterPropertiesSet() {
initHandlerMethods();
}
protected void initHandlerMethods() {
if (logger.isDebugEnabled()) {
logger.debug("Looking for request mappings in application context: " + getApplicationContext());
}
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;
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);
}
}
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
handlerMethodsInitialized(getHandlerMethods());
}
在initHandlerMethods方法中,做了以下工作:
- 首先通過
BeanFactoryUtils掃描應(yīng)用上下文,獲取所有的bean。 - 遍歷所有的
beanName,調(diào)用isHandler方法判斷是目標(biāo)bean是否包含@Controller或@RequestMapping注解。 - 對(duì)于帶有
@Controller或@RequestMapping注解的類,調(diào)用detectHandlerMethods委托處理,獲取所有的method,并調(diào)用registerHandlerMethod注冊(cè)所有的方法。
在detectHandlerMethods方法負(fù)責(zé)將Handler保存到Map中。
protected void detectHandlerMethods(final Object handler) {
// 獲取handler的類型
Class<?> handlerType = (handler instanceof String ?
getApplicationContext().getType((String) handler) : handler.getClass());
final Class<?> userType = ClassUtils.getUserClass(handlerType);
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
new MethodIntrospector.MetadataLookup<T>() {
@Override
public T inspect(Method method) {
try {
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);
}
}
selectMethods方法中重寫了MetadataLookup中的inspect方法,inspect方法中調(diào)用了子類RequestMappingHandlerMapping實(shí)現(xiàn)了getMappingForMethod模板方法,用于構(gòu)建RequestMappingInfo。
public static <T> Map<Method, T> selectMethods(Class<?> targetType, final MetadataLookup<T> metadataLookup) {
final Map<Method, T> methodMap = new LinkedHashMap<Method, T>();
Set<Class<?>> handlerTypes = new LinkedHashSet<Class<?>>();
Class<?> specificHandlerType = null;
if (!Proxy.isProxyClass(targetType)) {
handlerTypes.add(targetType);
specificHandlerType = targetType;
}
handlerTypes.addAll(Arrays.asList(targetType.getInterfaces()));
for (Class<?> currentHandlerType : handlerTypes) {
final Class<?> targetClass = (specificHandlerType != null ? specificHandlerType : currentHandlerType);
ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) {
Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
T result = metadataLookup.inspect(specificMethod);
if (result != null) {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
if (bridgedMethod == specificMethod || metadataLookup.inspect(bridgedMethod) == null) {
methodMap.put(specificMethod, result);
}
}
}
}, ReflectionUtils.USER_DECLARED_METHODS);
}
return methodMap;
}
在selectMethods通過反射獲取所有的方法,重寫了doWith方法,將handler中的method和請(qǐng)求對(duì)應(yīng)的RequestMappingInfo保存到methodMap中。
最終detectHandlerMethods將遍歷這個(gè)methodMap,調(diào)用registerHandlerMethod注冊(cè)HandlerMethod到MappingRegistry。
在AbstractHandlerMethodMapping類中,有個(gè)內(nèi)部類MappingRegistry,用來存儲(chǔ)mapping和 handler methods注冊(cè)關(guān)系,并提供了并發(fā)訪問方法。
AbstractHandlerMethodMapping通過getHandlerInternal來為一個(gè)請(qǐng)求選擇對(duì)應(yīng)的handler。
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
// 根據(jù)request獲取對(duì)應(yīng)的urlpath
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
if (logger.isDebugEnabled()) {
logger.debug("Looking up handler method for path " + lookupPath);
}
// 獲取讀鎖
this.mappingRegistry.acquireReadLock();
try {
// 調(diào)用lookupHandlerMethod方法獲取請(qǐng)求對(duì)應(yīng)的HandlerMethod
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的具體實(shí)現(xiàn)如下:
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<Match>();
// 通過lookupPath獲取所有匹配到的path
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
// 將匹配條件添加到matches
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
// 如果沒有匹配條件,將所有的匹配條件都加入matches
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);
}
// 選取排序后的第一個(gè)作為最近排序條件
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (CorsUtils.isPreFlightRequest(request)) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
// 前兩個(gè)匹配條件排序一樣拋出異常
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 + "}");
}
}
// 將lookupPath設(shè)為請(qǐng)求request的PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE屬性
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
}
}
整個(gè)過程以Match作為載體,Match是個(gè)內(nèi)部類,封裝了匹配條件和handlerMethod兩個(gè)屬性,默認(rèn)的實(shí)現(xiàn)是將lookupPath設(shè)置為請(qǐng)求的屬性。
總結(jié)
本文從源碼角度上分析了HandlerMapping的各種實(shí)現(xiàn)。主要功能是為請(qǐng)求找到合適的handler和interceptors,并組合成HandlerExecutionChain。查找handler的過程通過getHandlerInternal方法實(shí)現(xiàn),每個(gè)子類都其不同的實(shí)現(xiàn)。
所有的HandlerMapping的實(shí)現(xiàn)都繼承于AbstarctHandlerMapping,AbstarctHandlerMapping主要作用是完成攔截器的初始化工作。而通過AbstarctHandlerMapping又衍生出兩個(gè)系列,AbstractUrlHandlerMapping和AbstractHandlerMethodMapping。
AbstractUrlHandlerMapping也有很多子類的實(shí)現(xiàn),如SimpleUrlHandlerMapping、AbstractDetectingUrlHandlerMapping。總體來說,AbstractUrlHandlerMapping需要用到一個(gè)保存url和handler的對(duì)應(yīng)關(guān)系的map,map的初始化工作由子類實(shí)現(xiàn)。不同的子類會(huì)有自己的策略,可以在配置文件中注冊(cè),也可以在spring容器中找。
AbstractHandlerMethodMapping系列則通常用于注解的方法,解析包含@Controller或者@RequestMapping注解的類,建立url和method的直接對(duì)應(yīng)關(guān)系,這也是目前使用最多的一種方式。