HandlerMapping之RequestMappingHandlerMapping
一、HandlerMapping类图
默认情况下,SpringMVC 将加载当前系统中所有实现了HandlerMapping 接口的bean。如果只期望SpringMVC加载指定的handlermapping 时,可以修改web.xml中的DispatcherServlet的初始参数,将detectAllHandlerMappings的值设置为false:
<init-param>
<param-name>detectAllHandlerMappings</param-name>
<param-value> false</param-value>
</ init-param>
此时Spring MVC将查找名为“ handlerMapping”的bean, 并作为当前系统中唯一的handlermapping。如果没有定义handlerMapping 的话,则SpringMVC将按照org. Springframework.web.servlet.,DispatcherServlet所在目录下的DispatcherServlet.properties中所定义的org.Springframework.web.servlet.HandlerMapping的内容来加载默认的handlerMapping (用户没有自定义Strategies的情况下)。
二、初始化HandlerMethod
2.1 初始化HandlerMethod流程
(1) 获取容器中所有的Bean,筛选出类上有@Controller或@RequestMapping注解的类,作为候选Handler
(2) 遍历候选Bean所有方法,如果方法上没有@RequestMapping注解则忽略该方法,否则获取方法和类上的@RequestMapping注解并合并,创建RequestMappingInfo实例
(3) 注册RequestMappingInfo与HandlerMethod映射信息:
将Handler和Method封装到HandlerMethod中,建立RequestMappingInfo --> HandlerMethod映射关系
建立directUrl --> List<RequestMappingInfo>映射关系,同一个URL处理的请求方法不同:Get、Post等
建立name --> List<RequestMappingInfo>映射关系
建立HandlerMethod --> CorsConfiguration映射关系
建立RequestMappingInfo --> MappingRegistration映射关系,MappingRegistration封装了RequestMappingInfo、HandlerMethod、directUrls、name
2.2 RequestMappingHandlerMapping
2.2.1 afterPropertiesSet
从类图中可知RequestMappingHandlerMapping实现InitializingBean接口,下面看afterPropertiesSet方法
public void afterPropertiesSet() {
// 用于请求映射目的配置选项的容器。 创建RequestMappingInfo实例需要这种配置,但是通常在所有RequestMappingInfo实例中使用。
this.config = new RequestMappingInfo.BuilderConfiguration();
this.config.setUrlPathHelper(getUrlPathHelper());
this.config.setPathMatcher(getPathMatcher());
this.config.setSuffixPatternMatch(this.useSuffixPatternMatch);
this.config.setTrailingSlashMatch(this.useTrailingSlashMatch);
this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch);
this.config.setContentNegotiationManager(getContentNegotiationManager());
super.afterPropertiesSet();
}
2.2.2 getMappingForMethod
// 获取方法上的@RequestMapping注解,并创建RequestMappingInfo。调用者传送门:2.3.5
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
info = typeInfo.combine(info);
}
String prefix = getPathPrefix(handlerType);
if (prefix != null) {
info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info);
}
}
return info;
}
2.2.3 根据@RequestMapping创建RequestMappingInfo createRequestMappingInfo
根据@RequestMapping注解创建RequestMappingInfo时,有getCustomTypeCondition、getCustomMethodCondition这两个方法值得我们关注,可以扩展RequestMappingHandlerMapping实现@RequestMapping注解上的自定义RequestCondition。那么RequestCondition在哪里会用到呢?传送门:4.1
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
RequestCondition<?> condition = (element instanceof Class ?
getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
}
protected RequestMappingInfo createRequestMappingInfo(
RequestMapping requestMapping, @Nullable RequestCondition<?> customCondition) {
RequestMappingInfo.Builder builder = RequestMappingInfo
.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
.methods(requestMapping.method())
.params(requestMapping.params())
.headers(requestMapping.headers())
.consumes(requestMapping.consumes())
.produces(requestMapping.produces())
.mappingName(requestMapping.name());
if (customCondition != null) {
builder.customCondition(customCondition);
}
return builder.options(this.config).build();
}
2.3 AbstractHandlerMethodMapping
2.3.1 afterPropertiesSet
public void afterPropertiesSet() {
initHandlerMethods();
}
2.3.2 initHandlerMethods
protected void initHandlerMethods() {
for (String beanName : getCandidateBeanNames()) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
processCandidateBean(beanName);
}
}
// 输出总计包括检测到的映射+通过registerMapping的显式注册
handlerMethodsInitialized(getHandlerMethods());
}
2.3.3 获取候选Bean名称 getCandidateBeanNames
// 在应用程序上下文中确定候选bean的名称
protected String[] getCandidateBeanNames() {
return (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
obtainApplicationContext().getBeanNamesForType(Object.class));
}
2.3.4 处理候选Bean processCandidateBean
// 确定指定的候选bean的类型,如果标识为handler类型,则调用 {@link #detectHandlerMethods}
protected void processCandidateBean(String beanName) {
Class<?> beanType = null;
try {
beanType = obtainApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isTraceEnabled()) {
logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
}
}
// isHandler由子类实现,类上有@Controller或@RequestMapping注解
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
2.3.5 查找Handler中处理请求方法 detectHandlerMethods
// 在指定的handler bean中查找处理程序方法。{@link #detectHandlerMethods}避免了bean的创建。
protected void detectHandlerMethods(Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
Class<?> userType = ClassUtils.getUserClass(handlerType);
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> {
try {
// 子类实现获取方法或类上的@RequestMapping,封装为RequestMappingInfo。方法上有@RequestMapping时才会获取类上的@RequestMapping。传送门:2.2.2
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
throw new IllegalStateException("Invalid mapping on handler class [" +
userType.getName() + "]: " + method, ex);
}
});
if (logger.isTraceEnabled()) {
logger.trace(formatMappings(userType, methods));
}
methods.forEach((method, mapping) -> {
// 在目标类型上选择一个可调用的方法:给定方法本身(如果实际在目标类型上公开),或者在目标类型的一个接口或目标类型本身上对应的方法。
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
2.3.6 注册Handler中处理请求方法 registerHandlerMethod
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
this.mappingRegistry.register(mapping, handler, method);
}
2.4 HandlerMethod注册容器 MappingRegistry
2.4.1 注册HandlerMethod register
// RequestMappingInfo --> MappingRegistration<RequestMappingInfo>
private final Map<T, MappingRegistration<T>> registry = new HashMap<>();
// RequestMappingInfo --> HandlerMethod
private final Map<T, HandlerMethod> mappingLookup = new LinkedHashMap<>();
// url(@RequestMapping注解上配置的) --> RequestMappingInfo
private final MultiValueMap<String, T> urlLookup = new LinkedMultiValueMap<>();
// name(HandlerMethodMappingNamingStrategy生成) --> List<HandlerMethod>
private final Map<String, List<HandlerMethod>> nameLookup = new ConcurrentHashMap<>();
// HandlerMethod --> CorsConfiguration
private final Map<HandlerMethod, CorsConfiguration> corsLookup = new ConcurrentHashMap<>();
public void register(T mapping, Object handler, Method method) {
this.readWriteLock.writeLock().lock();
try {
// 创建HandlerMethod实例,封装了handler、method
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
assertUniqueMethodMapping(handlerMethod, mapping);
this.mappingLookup.put(mapping, handlerMethod);
// 获取@RequestMapping注解上配置的非正则表达式路径
List<String> directUrls = getDirectUrls(mapping);
for (String url : directUrls) {
this.urlLookup.add(url, mapping);
}
String name = null;
if (getNamingStrategy() != null) {
name = getNamingStrategy().getName(handlerMethod, mapping);
addMappingName(name, handlerMethod);
}
// 方法或类上的@CrossOrigin注解,封装成CorsConfiguration,由子类实现
CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
if (corsConfig != null) {
this.corsLookup.put(handlerMethod, corsConfig);
}
this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name));
}
finally {
this.readWriteLock.writeLock().unlock();
}
}
2.4.2 校验映射关系是否唯一 assertUniqueMethodMapping
private void assertUniqueMethodMapping(HandlerMethod newHandlerMethod, T mapping) {
HandlerMethod handlerMethod = this.mappingLookup.get(mapping);
if (handlerMethod != null && !handlerMethod.equals(newHandlerMethod)) {
throw new IllegalStateException(
"Ambiguous mapping. Cannot map '" + newHandlerMethod.getBean() + "' method \n" +
newHandlerMethod + "\nto " + mapping + ": There is already '" +
handlerMethod.getBean() + "' bean method\n" + handlerMethod + " mapped.");
}
}
三、根据请求获取 HandlerExecutionChain
3.1 获取HandlerMethod流程
(1) 根据请求URL获取直接匹配的List<RequestMappingInfo>作为候选,如果没有则取所有的RequestMappingInfo作为候选,遍历候选的RequestMappingInfo,调用RequestMappingInfo#
getMatchingCondition方法(返回不为NULL则匹配),获取匹配的List<RequestMappingInfo>。可以扩展实现自定义匹配规则,传送门:2.1.3
(2) 如果没有匹配的RequestMappingInfo,按照具体不匹配原因抛出对应异常,比如:请求方法不匹配、请求参数类型不匹配、响应类型不匹配、方法参数缺失等
(3) 如果有多个匹配的RequestMappingInfo,OPTION请求则会直接返回,否则找出最匹配的RequestMappingInfo,如果有多个匹配度相同的RequestMappingInfo则抛出异常。
3.2 AbstractHandlerMapping
3.2.1 获取请求对应的HandlerExecutionChain getHandler
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
// 查找给定请求的Handler,如果未找到特定Handler,则返回{@code null}。如果返回{@code null}值,则使用默认Handler。留给子类实现,传送门:3.3.1
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
if (handler instanceof String) {
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
// handler和interceptor(匹配的MappedInterceptor)封装为HandlerExecutionChain
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (logger.isTraceEnabled()) {
logger.trace("Mapped to " + handler);
}
else if (logger.isDebugEnabled() && !request.getDispatcherType().equals(DispatcherType.ASYNC)) {
logger.debug("Mapped to " + executionChain.getHandler());
}
if (CorsUtils.isCorsRequest(request)) {
// 全剧跨域配置
CorsConfiguration globalConfig = this.corsConfigurationSource.getCorsConfiguration(request);
// 匹配请求的跨域配置:如果handler是CorsConfigurationSource,获取request的跨域配置
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
// 全剧跨域配置 + 匹配请求的跨域配置
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
3.2.2 封装Handler和请求对应的拦截器链 getHandlerExecutionChain
// handler和interceptor(匹配的MappedInterceptor)封装为HandlerExecutionChain
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?
(HandlerExecutionChain) handler : new HandlerExecutionChain(handler));
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {
chain.addInterceptor(mappedInterceptor.getInterceptor());
}
}
else {
chain.addInterceptor(interceptor);
}
}
return chain;
}
3.2.3 获取请求对应的跨域配置 getCorsConfiguration
// 如果handler是CorsConfigurationSource,获取request的跨域配置
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
Object resolvedHandler = handler;
if (handler instanceof HandlerExecutionChain) {
resolvedHandler = ((HandlerExecutionChain) handler).getHandler();
}
if (resolvedHandler instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource) resolvedHandler).getCorsConfiguration(request);
}
return null;
}
3.2.4 生成带跨域配置的HandlerExecutionChain getCorsHandlerExecutionChain
protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request,
HandlerExecutionChain chain, @Nullable CorsConfiguration config) {
if (CorsUtils.isPreFlightRequest(request)) {
HandlerInterceptor[] interceptors = chain.getInterceptors();
chain = new HandlerExecutionChain(new PreFlightHandler(config), interceptors);
}
else {
chain.addInterceptor(new CorsInterceptor(config));
}
return chain;
}
3.3 AbstractHandlerMethodMapping
3.3.1 获取请求对应的HandlerMethod getHandlerInternal
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
// this.mappingRegistry初始化时注册RequestMappingInfo 传送门:2.1.2.6、2.1.2.7
this.mappingRegistry.acquireReadLock();
try {
HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
}
finally {
this.mappingRegistry.releaseReadLock();
}
}
3.3.2 查找匹配请求的HandlerMethod lookupHandlerMethod
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
// Match封装了HandlerMethod和RequestMappingInfo
List<Match> matches = new ArrayList<>();
// 根据请求URL获取直接匹配的List<RequestMappingInfo>
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
// 获取匹配请求的处理方法:调用RequestMappingInfo#getMatchingCondition返回不为NULL则匹配
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
// 除了浏览所有mappings外别无选择。this.mappingRegistry.getMappings().keySet()获取所有的RequestMappingInfo,遍历找到匹配的处理方法
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}
if (!matches.isEmpty()) {
// 由子类实现,getMappingComparator 获取RequestMappingInfo比较器
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
matches.sort(comparator);
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (logger.isTraceEnabled()) {
logger.trace(matches.size() + " matching mappings: " + matches);
}
// OPTION请求直接返回
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();
String uri = request.getRequestURI();
throw new IllegalStateException(
"Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
}
}
// 在请求中保存最匹配的处理方法
request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, bestMatch.handlerMethod);
// 由子类实现:在请求中公开URI模板变量,矩阵变量和可生产的媒体类型,在请求中保存了一些属性
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
}
}
3.3.3 获取匹配请求的HandlerMethod addMatchingMappings
private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
for (T mapping : mappings) {
// 由子类实现,检查给定的RequestMappingInfo是否与当前请求匹配,调用RequestMappingInfo#getMatchingCondition
T match = getMatchingMapping(mapping, request);
if (match != null) {
matches.add(new Match(match, this.mappingRegistry.getMappings().get(mapping)));
}
}
}
3.4 RequestMappingInfoHandlerMapping
3.4.1 检查给定的RequestMappingInfo是否与当前请求匹配 getMatchingMapping
// 检查给定的RequestMappingInfo是否与当前请求匹配,并返回一个(可能是新的)实例,该实例具有与当前请求匹配的条件-例如带有URL模式的子集。
protected RequestMappingInfo getMatchingMapping(RequestMappingInfo info, HttpServletRequest request) {
return info.getMatchingCondition(request);
}
3.4.2 匹配当前请求设置属性 handleMatch
// 在请求中公开URI模板变量,矩阵变量和可生产的媒体类型
protected void handleMatch(RequestMappingInfo info, String lookupPath, HttpServletRequest request) {
super.handleMatch(info, lookupPath, request);
String bestPattern;
Map<String, String> uriVariables;
Set<String> patterns = info.getPatternsCondition().getPatterns();
if (patterns.isEmpty()) {
bestPattern = lookupPath;
uriVariables = Collections.emptyMap();
}
else {
bestPattern = patterns.iterator().next();
uriVariables = getPathMatcher().extractUriTemplateVariables(bestPattern, lookupPath);
}
request.setAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern);
if (isMatrixVariableContentAvailable()) {
Map<String, MultiValueMap<String, String>> matrixVars = extractMatrixVariables(request, uriVariables);
request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, matrixVars);
}
Map<String, String> decodedUriVariables = getUrlPathHelper().decodePathVariables(request, uriVariables);
request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedUriVariables);
if (!info.getProducesCondition().getProducibleMediaTypes().isEmpty()) {
Set<MediaType> mediaTypes = info.getProducesCondition().getProducibleMediaTypes();
request.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
}
}
3.4.3 针对不匹配请求返回具体异常 handleNoMatch
protected HandlerMethod handleNoMatch(
Set<RequestMappingInfo> infos, String lookupPath, HttpServletRequest request) throws ServletException {
PartialMatchHelper helper = new PartialMatchHelper(infos, request);
if (helper.isEmpty()) {
return null;
}
if (helper.hasMethodsMismatch()) {
Set<String> methods = helper.getAllowedMethods();
if (HttpMethod.OPTIONS.matches(request.getMethod())) {
HttpOptionsHandler handler = new HttpOptionsHandler(methods);
return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
}
// 请求处理程序不支持特定请求方法时引发的异常
throw new HttpRequestMethodNotSupportedException(request.getMethod(), methods);
}
if (helper.hasConsumesMismatch()) {
Set<MediaType> mediaTypes = helper.getConsumableMediaTypes();
MediaType contentType = null;
if (StringUtils.hasLength(request.getContentType())) {
try {
contentType = MediaType.parseMediaType(request.getContentType());
}
catch (InvalidMediaTypeException ex) {
throw new HttpMediaTypeNotSupportedException(ex.getMessage());
}
}
// 当客户端POST,PUT或PATCH的内容不受请求处理程序支持时,抛出此异常
throw new HttpMediaTypeNotSupportedException(contentType, new ArrayList<>(mediaTypes));
}
if (helper.hasProducesMismatch()) {
Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
// 当请求处理程序无法生成客户端可接受的响应时引发的异常
throw new HttpMediaTypeNotAcceptableException(new ArrayList<>(mediaTypes));
}
if (helper.hasParamsMismatch()) {
List<String[]> conditions = helper.getParamConditions();
// {@link ServletRequestBindingException}子类,指示不满意的参数条件,通常使用{@code @Controller}类型级别的{@code @RequestMapping} 注释表示。
throw new UnsatisfiedServletRequestParameterException(conditions, request.getParameterMap());
}
return null;
}
四、RequestMappingInfo
4.1 检查给定的RequestMappingInfo是否与当前请求匹配 getMatchingCondition
public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
RequestMethodsRequestCondition methods = this.methodsCondition.getMatchingCondition(request);
if (methods == null) {
return null;
}
ParamsRequestCondition params = this.paramsCondition.getMatchingCondition(request);
if (params == null) {
return null;
}
HeadersRequestCondition headers = this.headersCondition.getMatchingCondition(request);
if (headers == null) {
return null;
}
ConsumesRequestCondition consumes = this.consumesCondition.getMatchingCondition(request);
if (consumes == null) {
return null;
}
ProducesRequestCondition produces = this.producesCondition.getMatchingCondition(request);
if (produces == null) {
return null;
}
PatternsRequestCondition patterns = this.patternsCondition.getMatchingCondition(request);
if (patterns == null) {
return null;
}
// 自定义匹配规则 传送门:2.2.3
RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
if (custom == null) {
return null;
}
return new RequestMappingInfo(this.name, patterns,
methods, params, headers, consumes, produces, custom.getCondition());
}