目录
- 定位HandlerMethod
- RequestMappingInfoHandlerMapping提供的getHandlerInternal实现
- AbstractHandlerMethodMapping提供的getHandlerInternal实现
- 使用案例
如果是通过请求路径去映射集合中通过精确匹配进行查询的话,其实实现起来就很简单了,但是因为要加入@RequestMapping中相关请求限制,包括通配符匹配和占位符匹配等等内容,会让寻找HandlerMethod的过程变的不那么简单,但是也没有那么复杂,下面我们就来看看。
定位HandlerMethod
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
....
//检查是否是文件上传请求,如果是的话,就返回封装后的MultipartHttpServletRequest
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
//通过当前请求定位到具体处理的handler--这里是handlerMethod
mappedHandler = getHandler(processedRequest);
....
我们本节的重点就在getHandler方法中:
@Nullable
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping mapping : this.handlerMappings) {
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
getHandler方法中会遍历所有可用的HandlerMapping,然后尝试通过当前请求解析得到一个handler,如果不为空,说明找到了,否则借助下一个HandlerMapping继续寻找。
前面已经说过了,注解Controller的映射建立是通过RequestMappingHandlerMapping完成的,那么寻找映射当然也需要通过RequestMappingHandlerMapping完成,因此我们这里只关注RequestMappingHandlerMapping的getHandler流程链即可。
getHandler方法主要是由AbstractHandlerMapping顶层抽象基类提供了一个模板方法实现,具体根据request寻找handler的逻辑实现,是通过getHandlerInternal抽象方法交给子类实现的。
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
//这里调用到的是RequestMappingInfoHandlerMapping子类提供的实现
Object handler = getHandlerInternal(request);
//如果没找到,尝试寻找兜底的默认handler
if (handler == null) {
handler = getDefaultHandler();
}
//如果还是兜底也不管用,就返回null
if (handler == null) {
return null;
}
//如果此时的handler拿到的还只是一个字符串名字,那么需要先去容器得到对应的实体对象
if (handler instanceof String) {
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
...
//构建拦截器链
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
...
//跨域处理
if (hasCorsConfigurationSource(handler) || CorsUtils.isPreFlightRequest(request)) {
...
}
return executionChain;
}
RequestMappingInfoHandlerMapping提供的getHandlerInternal实现
RequestMappingInfoHandlerMapping主要作为RequestMappingInfo,Request和HandlerMethod三者之间沟通的桥梁,RequestMappingInfo提供请求匹配条件,判断当前Request是否应该交给当前HandlerMethod处理
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
request.removeAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
try {
//调用父类AbstractHandlerMethodMapping的方法
return super.getHandlerInternal(request);
}
finally {
//把下面这个方法进行内联后,等价于 : request.removeAttribute(MEDIA_TYPES_ATTRIBUTE);
ProducesRequestCondition.clearMediaTypesAttribute(request);
}
}
清除Request相关属性,主要是因为Request对象会被复用,因此使用前,需要清空上一次的数据,这也算是对象复用增加的代码复杂性吧。
AbstractHandlerMethodMapping提供的getHandlerInternal实现
RequestMappingInfoHandlerMapping重写了父类的getHandlerInternal方法,但只是对Request对象复用进行了相关数据清除工作,核心还是在AbstractHandlerMethodMapping提供的getHandlerInternal实现中。
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
//initLookupPath默认是返回Context-path后面的路径
//eg1: 没有设置context-path,请求路径为localhost:5200/volunteer/back/admin/pass/login,那这里返回的就是/volunteer/back/admin/pass/login
//eg2: 上面的例子中设置了context-path为/volunteer,那这里返回的就是/back/admin/pass/login
String lookupPath = initLookupPath(request);
//获取读锁
this.mappingRegistry.acquireReadLock();
try {
//通过请求路径去映射集合中寻找对应的handlerMethod
HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
}
finally {
this.mappingRegistry.releaseReadLock();
}
}
initLookupPath方法中默认会返回的请求路径为剥离掉context-path后的路径,并且后续拦截器中进行路径匹配时,匹配的也是剥离掉context-path后的路径,这一点切记!
根据请求路径去映射集合中寻找HandlerMethod
lookupHandlerMethod是本文的核心关注点,该方法会通过Request定位到对应的HandlerMethod后返回。
具体处理过程,又可以分为三种情况:
- 精确匹配到一个结果
- 需要进行最佳匹配
- 没有匹配到任何结果
因为这部分逻辑比较复杂,因此我们对三种情况分开讨论
精确匹配到一个结果
@Nullable
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<>();
//先通过请求路径去pathLookup集合中尝试进行精准匹配--这里的T指的是RequestMappingInfo
List<T> directPathMatches = this.mappingRegistry.getMappingsByDirectPath(lookupPath);
//精准匹配到了结果
if (directPathMatches != null) {
//将结果添加进matches集合中--还会经过RequstMappingInfo的条件校验环节
addMatchingMappings(directPathMatches, matches, request);
}
//如果上面精确匹配没有匹配到结果----
if (matches.isEmpty()) {
//将register的keySet集合保存的所有RequestMappingInfo都加入matches集合中去
//然后依次遍历每个RequstMappingInfo,通过其自身提供的getMatchingCondition对当前requst请求进行条件匹配
//如果不满足条件,是不会加入到当前matches集合中去的
addMatchingMappings(this.mappingRegistry.getRegistrations().keySet(), matches, request);
}
if (!matches.isEmpty()) {
//获取matches集合中第一个元素
Match bestMatch = matches.get(0);
//如果matches集合元素大于0,说明需要进一步进行模糊搜索
if (matches.size() > 1) {
...
}
//在request对象的属性集合中设置处理当前请求的HandlerMethod
request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, bestMatch.getHandlerMethod());
//处理当前最佳匹配
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.getHandlerMethod();
}
else {
//没有匹配结果
return handleNoMatch(this.mappingRegistry.getRegistrations().keySet(), lookupPath, request);
}
}
addMatchingMappings将得到的匹配结果RequestMappingInfo加入matches集合,但这个过程中还需要进行一些特殊处理,例如:
@PostMapping({PASS+"login",PASS+"log"})
此时PostMapping会映射到两种请求路径上,此时这里需要做的就是,搞清楚到底是哪一个路径匹配上了当前请求,然后修改RequestMappingInfo对应的patterns集合,将多余的请求路径去除掉。
还有就是一个请求路径可能会映射到多个RequestMappingInfo上,例如:
请求路径相同,只是请求方法不同。
private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
//遍历每个RequestMappinginfo
for (T mapping : mappings) {
//判断当前RequestMappingInfo是否能够真正映射到当前请求上
T match = getMatchingMapping(mapping, request);
//如果返回值不为空,表示可以映射,否则跳过处理下一个
if (match != null) {
matches.add(new Match(match, this.mappingRegistry.getRegistrations().get(mapping)));
}
}
}
getMatchingMapping的判断还是通过RequestMappingInfo自身提供的条件进行进行匹配的:
@Override
protected RequestMappingInfo getMatchingMapping(RequestMappingInfo info, HttpServletRequest request) {
return info.getMatchingCondition(request);
}
检查当前RequestMappingInfo 中的所有条件是否与提供的请求匹配,并返回一个新的RequestMappingInfo,其中包含针对当前请求量身定制的条件。
例如,返回的实例可能包含与当前请求匹配的 URL 模式的子集,并以最佳匹配模式在顶部进行排序。
@Override
@Nullable
public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
//检查@RequestMapping注解提供的method请求方式是否与当前请求匹配,如果不匹配返回null
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;
}
//Consume条件检查
ConsumesRequestCondition consumes = this.consumesCondition.getMatchingCondition(request);
if (consumes == null) {
return null;
}
//Produce条件检查
ProducesRequestCondition produces = this.producesCondition.getMatchingCondition(request);
if (produces == null) {
return null;
}
//PathPatternsRequestCondition一般为null
PathPatternsRequestCondition pathPatterns = null;
if (this.pathPatternsCondition != null) {
pathPatterns = this.pathPatternsCondition.getMatchingCondition(request);
if (pathPatterns == null) {
return null;
}
}
//@PostMapping({PASS+"login",PASS+"log"})的情况处理
//RequestMappingInfo中的patterns数组中如果存在多个请求路径,需要判断当前请求是具体映射到了那个路径上
//然后重新构造一个patternsCondition后返回,该patternsCondition内部包含的只有匹配当前请求路径的那个pattern
PatternsRequestCondition patterns = null;
if (this.patternsCondition != null) {
patterns = this.patternsCondition.getMatchingCondition(request);
if (patterns == null) {
return null;
}
}
//自定义请求限制
RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
if (custom == null) {
return null;
}
//上面这些条件其中一个不通过,那么返回的结果就为null
//最后构造一个全新的RequestMappingInfo返回,该RequestMappingInfo中包含的都是匹配上当前请求路径的信息,排除了其他非匹配上的信息
return new RequestMappingInfo(this.name, pathPatterns, patterns,
methods, params, headers, consumes, produces, custom, this.options);
}
handleMatch法主要是针对模糊匹配出来的结果进行相关处理,例如: URI template variables,matrix variables和producible media types处理等等…
上面这些名词关联的注解有: @PathVariable , @MatrixVariable ,producible media types对应的是@RequestMapping中produces设置。
@Override
protected void handleMatch(RequestMappingInfo info, String lookupPath, HttpServletRequest request) {
super.handleMatch(info, lookupPath, request);
//一般返回的就是@RequestMapping注解中的patterns属性,注意@RequestMapping注解可以映射到多个URL上
//这里返回的就是patterns属性对应的patternsCondition请求匹配条件对象
RequestCondition<?> condition = info.getActivePatternsCondition();
//condition默认实现为patternsCondition,因此这里直接走else分支
if (condition instanceof PathPatternsRequestCondition) {
extractMatchDetails((PathPatternsRequestCondition) condition, lookupPath, request);
}
else {
//抽取匹配细节,该方法内部会完成对上面这些模板变量,矩阵变量的处理
extractMatchDetails((PatternsRequestCondition) condition, lookupPath, request);
}
//如果我们设置了@RequestMapping注解中的produces属性,那么这里会进行处理
if (!info.getProducesCondition().getProducibleMediaTypes().isEmpty()) {
Set<MediaType> mediaTypes = info.getProducesCondition().getProducibleMediaTypes();
//设置到request对象的属性集合中,不用想,肯定会在响应的时候用到
request.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
}
}
父类AbstractHandlerMethodMapping中的handleMatch方法,主要是将lookup设置到当前请求对象的属性集合中去:
protected void handleMatch(T mapping, String lookupPath, HttpServletRequest request) {
request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, lookupPath);
}
矩阵匹配不多讲,因为我也不会。
匹配失败
如果没有寻找当前一个RequestMappingInfo能够处理当前request,那么进入handleNoMatch阶段。handleNoMatch会再次迭代所有 RequestMappingInfo,至少通过 URL 查看是否有任何匹配,并根据不匹配的内容引发异常。说人话就是找出不匹配的原因,然后抛出对应的异常,告诉用户。
@Override
protected HandlerMethod handleNoMatch(
Set<RequestMappingInfo> infos, String lookupPath, HttpServletRequest request) throws ServletException {
//借助PartialMatchHelper来分析那些部分匹配的请求,是因为什么原因而无法匹配成功的
//部分匹配的意思就是请求路径匹配上了,但是因为其他条件匹配失败了,例如: 请求头限制等
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())) {
Set<MediaType> mediaTypes = helper.getConsumablePatchMediaTypes();
HttpOptionsHandler handler = new HttpOptionsHandler(methods, mediaTypes);
return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
}
throw new HttpRequestMethodNotSupportedException(request.getMethod(), methods);
}
//consume条件不满足
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());
}
}
throw new HttpMediaTypeNotSupportedException(contentType, new ArrayList<>(mediaTypes));
}
//produces条件不满足
if (helper.hasProducesMismatch()) {
Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
throw new HttpMediaTypeNotAcceptableException(new ArrayList<>(mediaTypes));
}
//请求参数条件不满足
if (helper.hasParamsMismatch()) {
List<String[]> conditions = helper.getParamConditions();
throw new UnsatisfiedServletRequestParameterException(conditions, request.getParameterMap());
}
return null;
}
PartialMatchHelper会首先获取到所有请求路径匹配成功的RequestMappingInfo:
public PartialMatchHelper(Set<RequestMappingInfo> infos, HttpServletRequest request) {
for (RequestMappingInfo info : infos) {
if (info.getActivePatternsCondition().getMatchingCondition(request) != null) {
this.partialMatches.add(new PartialMatch(info, request));
}
}
}
PartialMatch的构造方法会判断当前RequestMappingInfo不匹配的原因是什么:
public PartialMatch(RequestMappingInfo info, HttpServletRequest request) {
this.info = info;
this.methodsMatch = (info.getMethodsCondition().getMatchingCondition(request) != null);
this.consumesMatch = (info.getConsumesCondition().getMatchingCondition(request) != null);
this.producesMatch = (info.getProducesCondition().getMatchingCondition(request) != null);
this.paramsMatch = (info.getParamsCondition().getMatchingCondition(request) != null);
}
相关has*Mismatch就是遍历partialMatches集合,然后挨个判断是否存在对应的不匹配原因:
public boolean hasMethodsMismatch() {
for (PartialMatch match : this.partialMatches) {
if (match.hasMethodsMatch()) {
return false;
}
}
return true;
}
根据request请求去HandlerMethod注册中心寻找对应HandlerMethod的过程就分析完毕了,下一节,会对handlerMethod的调用过程进行分析。
使用案例
1、问题
后端服务在提供api接口时,随着业务的变化,原有的接口很有可能不能满足现有的需求。在无法修改原有接口的情况下,只能提供一个新版本的接口来开放新的业务能力。
区分不同版本的api接口的方式有多种,其中一种简单通用的方式是在uri中添加版本的标识,例如/api/v1/user
,api/v3/user
。通过v+版本号来指定不同版本的api接口。在后端服务的代码中,可以将版本号直接写入代码中,例如,user接口提供两个入口方法,url mapping分别指定为/api/v1/user
和/api/v2/user
。
这种方式主要有几个缺陷:
- 通常为了统一控制,调用方会使用统一一个版本来调用接口。如果后端服务在升级接口的版本时,实际只需要变更其中几个接口的逻辑,其余接口只能通过添加新的mapping来完成升级。
- 接口的优先匹配,当调用高版本的api接口时,理论应该访问当前最高版本的接口,例如,如果当前整体api版本为4,但是实际上
/user
接口的mapping配置最高版本为v2
,这时使用v4
或者v2
调用/user
接口时,都应该返回/v2/user
的结果。
2、解决方式
为了较好地解决上面的问题,需要从SpringMVC对uri映射到接口的逻辑做一个扩展。
3、SpringMVC映射请求到处理方法的过程
SpringMVC处理请求分发的过程中主要的几个类为:
HandlerMapping
: 定义根据请求获取处理当期请求的HandlerChain的getHandler
方法,其中包括实际处理逻辑的handler对象和拦截器
AbstractHandlerMapping
: 实现HandlerMapping
接口的抽象类,在getHandler
方法实现了拦截器的初始化和handler对象获取,其中获取handler对象的getHandlerInternal
方法为抽象方法,由子类实现
AbstractHandlerMethodMapping<T>
: 继承AbstractHandlerMapping
,定义了method handler映射关系,每一个method handler都一个唯一的T关联
RequestMappingInfoHandlerMapping
: 继承``AbstractHandlerMethodMapping
RequestMappingInfo
: 包含各种匹配规则RequestCondition,请求到method的映射规则信息都包含在这个对象中
Condition | 说明 |
---|---|
PatternsRequestCondition | url匹配规则 |
RequestMethodsRequestCondition | http方法匹配规则,例如GET,POST等 |
ParamsRequestCondition | 参数匹配规则 |
HeadersRequestCondition | http header匹配规则 |
ConsumesRequestCondition | 请求Content-Type头部的媒体类型匹配规则 |
ProducesRequestCondition | 请求Accept头部媒体类型匹配规则 |
RequestCondition | 自定义condition |
RequestMappingHandlerMapping
: 继承RequestMappingInfoHandlerMapping
,处理方法的@ReqeustMapping
注解,将其与method handler与@ReqeustMapping
注解构建的RequestMappingInfo
关联
3.1、Spring初始化RequestMappingInfo与handler的关系
Spring在初始化RequestMappingHandlerMapping
Bean的时候,会初始化Controller的方法与RequestMappingInfo的映射关系并缓存,方便请求过来时,查询使用。
RequestMappingHandlerMapping
实现了InitializingBean
接口(父类实现),接口说明如下:
/**
* Interface to be implemented by beans that need to react once all their
* properties have been set by a BeanFactory: for example, to perform custom
* initialization, or merely to check that all mandatory properties have been set.
*/
public interface InitializingBean {
/**
* BeanFactory初始化bean的属性完成后会调用当前方法
*/
void afterPropertiesSet() throws Exception;
}
当RequestMappingHandlerMapping
Bean属性初始化完成之后,BeanFactory对调用afterPropertiesSet
方法:
@Override
public void afterPropertiesSet() {
//初始化handler methods
initHandlerMethods();
}
protected void initHandlerMethods() {
...
// 查询所有bean,分别检测是否有@Controller和@RequestMapping配置
String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
obtainApplicationContext().getBeanNamesForType(Object.class));
for (String beanName : beanNames) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
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.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
// 只处理注解了@Controller或@RequestMapping,@RestController、@GetMapping等也
// 符合条件
if (beanType != null && isHandler(beanType)) {
// 检测Mapping并注册
detectHandlerMethods(beanName);
}
}
}
// 空实现
handlerMethodsInitialized(getHandlerMethods());
}
detectHandlerMethods
方法会将Controller中所以可以检测到RequestCondition的方法抽取出来,并将包含RequestCondition集合的对象RequestMappingInfo一起注册,RequestCondition集合包括所有配置的规则,例如:
@RequestMapping(value = "/test", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
detectHandlerMethods
方法:
protected void detectHandlerMethods(final Object handler) {
// handlerType有可能是beanName,获取bean实例
Class<?> handlerType有可能是beanName = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
// 获取实际的Controller Class对象,处理CGLIB代理类的情况,拿到被代理的Class对象
final Class<?> userType = ClassUtils.getUserClass(handlerType);
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> {
try {
// 实际获取RequestMappingInfo
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);
}
methods.forEach((method, mapping) -> {
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
// 注册RequestMappingInfo和method的关联关系
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
getMappingForMethod
方法中,将方法与类中的@RequestMapping注解信息结合,同时获取用户自定义的RequestCondition,将所有的condition组合成一个RequestMappingInfo返回,获取不到则返回null。
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
// 获取方法的RequestMappingInfo,包括自定义的RequestCondition
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
// 获取类的RequestMappingInfo,包括自定义的RequestCondition
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
info = typeInfo.combine(info);
}
}
return info;
}
// 获取RequestMappingInfo
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
// 获取@RequestMapping注解
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
// 获取自定义的RequestCondition
RequestCondition<?> condition = (element instanceof Class ?
getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
// 组合自定义的RequestCondition与@RequestMapping的信息返回RequestMappingInfo
return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
}
3.2、Spring根据mapping关系查询处理请求的方法
主要功能入口在AbstractHandlerMethodMapping
的lookupHandlerMethod
方法,首先根据上一节注册的@RequestMapping配置的uri直接查询是否有对应的处理方法,如果查询不到,例如url配置中有占位符,不能直接匹配上,则遍历Mapping缓存查询:
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<>();
// 1.直接根据url查询关联
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
// 2.直接根据url查询不到,遍历映射缓存,确认是否有匹配的handler方法
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}
// 3.如果有多个匹配,根据规则做一个排序,拿最佳匹配的handler,如果无法区分就会报错
...
}
在步骤2中,会将缓存中的RequestMappingInfo查询出来,并对当前HttpServletRequest做一个匹配,主要逻辑是使用RequestMappingInfo中保存的各种RequestCondition匹配当前请求,也包括自定义的RequestCondition,返回匹配结果,主要的方法为RequestMappingInfo的getMatchingCondition
:
public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
// 使用当前对象保存的RequestMethodsRequestCondition信息匹配request
RequestMethodsRequestCondition methods = this.methodsCondition.getMatchingCondition(request);
// 使用当前对象保存的ParamsRequestCondition信息匹配request
ParamsRequestCondition params = this.paramsCondition.getMatchingCondition(request);
HeadersRequestCondition headers = this.headersCondition.getMatchingCondition(request);
ConsumesRequestCondition consumes = this.consumesCondition.getMatchingCondition(request);
ProducesRequestCondition produces = this.producesCondition.getMatchingCondition(request);
if (methods == null || params == null || headers == null || consumes == null || produces == null) {
return null;
}
PatternsRequestCondition patterns = this.patternsCondition.getMatchingCondition(request);
if (patterns == null) {
return null;
}
// 使用当前对象保存的自定义的RequestCondition信息匹配request
RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
if (custom == null) {
return null;
}
// 如果匹配,返回匹配的结果
return new RequestMappingInfo(this.name, patterns,
methods, params, headers, consumes, produces, custom.getCondition());
}
将请求分发到具体的Controller方法的逻辑主要是初始化过程中注册的Mapping缓存(RequestMappingInfo)查找与匹配的过程,RequestMappingInfo中包含各种RequestCondition,包括参数、HTTP方法、媒体类型等规则的匹配,同时还包含了一个自定义的RequestCondition的扩展,如果想要增加自定义的Request匹配规则,就可以从这里入手。
3.3、小结
在RequestMappingHandlerMapping进行初始化接口回调的时候,会来创建RequestMappingInfo对象
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
// 创建的时候会获取得到RequestCondition
RequestCondition<?> condition = (element instanceof Class ?
getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
}
但是因为当前RequestMappingHandlerMapping中,对于:
protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
return null;
}
protected RequestCondition<?> getCustomMethodCondition(Method method) {
return null;
}
都是空实现,所以说这里的RequestCondition默认就是空的。所以在类和方法上都没有条件注解使用。
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;
}
看看具体的合并操作过程:
public RequestMappingInfo combine(RequestMappingInfo other) {
String name = combineNames(other);
PathPatternsRequestCondition pathPatterns =
(this.pathPatternsCondition != null && other.pathPatternsCondition != null ?
this.pathPatternsCondition.combine(other.pathPatternsCondition) : null);
PatternsRequestCondition patterns =
(this.patternsCondition != null && other.patternsCondition != null ?
this.patternsCondition.combine(other.patternsCondition) : null);
RequestMethodsRequestCondition methods = this.methodsCondition.combine(other.methodsCondition);
ParamsRequestCondition params = this.paramsCondition.combine(other.paramsCondition);
HeadersRequestCondition headers = this.headersCondition.combine(other.headersCondition);
ConsumesRequestCondition consumes = this.consumesCondition.combine(other.consumesCondition);
ProducesRequestCondition produces = this.producesCondition.combine(other.producesCondition);
RequestConditionHolder custom = this.customConditionHolder.combine(other.customConditionHolder);
return new RequestMappingInfo(
name, pathPatterns, patterns, methods, params, headers, consumes, produces, custom);
}
看一下具体实现:
RequestConditionHolder custom = this.customConditionHolder.combine(other.customConditionHolder);
public RequestConditionHolder combine(RequestConditionHolder other) {
if (this.condition == null && other.condition == null) {
return this;
}
else if (this.condition == null) {
return other;
}
else if (other.condition == null) {
return this;
}
else {
assertEqualConditionTypes(this.condition, other.condition);
// 具体的在这里!将合并之后的放入到这里来
RequestCondition<?> combined = (RequestCondition<?>) this.condition.combine(other.condition);
return new RequestConditionHolder(combined);
}
}
看下使用的地方:
HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
重点看下这两行代码:
// directPathMatches,匹配到的路径
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
for (T mapping : mappings) {
T match = getMatchingMapping(mapping, request);
if (match != null) {
matches.add(new Match(match,
this.mappingRegistry.getRegistrations().get(mapping).getHandlerMethod()));
}
}
protected RequestMappingInfo getMatchingMapping(RequestMappingInfo info, HttpServletRequest request) {
return info.getMatchingCondition(request);
}
看看具体的代码:
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;
}
PathPatternsRequestCondition pathPatterns = null;
if (this.pathPatternsCondition != null) {
pathPatterns = this.pathPatternsCondition.getMatchingCondition(request);
if (pathPatterns == null) {
return null;
}
}
PatternsRequestCondition patterns = null;
if (this.patternsCondition != null) {
patterns = this.patternsCondition.getMatchingCondition(request);
if (patterns == null) {
return null;
}
}
// 找到这个hodler,如果没有,返回的RequestMappingInfo为null
RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
if (custom == null) {
return null;
}
return new RequestMappingInfo(
this.name, pathPatterns, patterns, methods, params, headers, consumes, produces, custom);
}
具体的就看下getMatchingCondition的实现
public RequestConditionHolder getMatchingCondition(HttpServletRequest request) {
// 正常为null
if (this.condition == null) {
return this;
}
RequestCondition<?> match = (RequestCondition<?>) this.condition.getMatchingCondition(request);
return (match != null ? new RequestConditionHolder(match) : null);
}
这里就直接调用condition.getMatchingCondition的方法来得到匹配RequestCondition,最终组成RequestMappingInfo。
如果最终都没有找到,那么将会执行到:
return handleNoMatch(this.mappingRegistry.getRegistrations().keySet(), lookupPath, request);
将最终的异常抛出。
4、自定义RequestCondition实现版本控制
RequestCondition定义:
public interface RequestCondition<T> {
/**
* 同另一个condition组合,例如,方法和类都配置了@RequestMapping的url,可以组合
*/
T combine(T other);
/**
* 检查request是否匹配,可能会返回新建的对象,例如,如果规则配置了多个模糊规则,可能当前请求
* 只满足其中几个,那么只会返回这几个条件构建的Condition
*/
@Nullable
T getMatchingCondition(HttpServletRequest request);
/**
* 比较,请求同时满足多个Condition时,可以区分优先使用哪一个
*/
int compareTo(T other, HttpServletRequest request);
}
同@RequestMapping一样,我们同样定义一个自定义注解,来保存接口方法的规则信息:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiVersion {
// 定义接口的版本号
int value() default 1;
}
自定义一个新的RequestCondition:
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {
// 用于匹配request中的版本号 v1 v2
private static final Pattern VERSION_PATTERN = Pattern.compile("/v(\\d+).*");
// 保存当前的版本号
private int version;
// 保存所有接口的最大版本号
private static int maxVersion = 1;
public ApiVersionRequestCondition(int version) {
this.version = version;
}
// 组合,看看是怎么组合。使用它们的,还是我们自己的?
// 又该怎么来进行组合
@Override
public ApiVersionRequestCondition combine(ApiVersionRequestCondition other) {
// 上文的getMappingForMethod方法中是使用 类的Condition.combine(方法的condition)的结果
// 确定一个方法的condition,所以偷懒的写法,直接返回参数的版本,可以保证方法优先,可以优化
// 在condition中增加一个来源于类或者方法的标识,以此判断,优先整合方法的condition
return new ApiVersionRequestCondition(other.version);
}
// 返回匹配条件,也就是使用哪个RequestCondition
@Override
public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {
// 正则匹配请求的uri,看是否有版本号 v1
Matcher matcher = VERSION_PATTERN.matcher(request.getRequestURI());
if (matcher.find()) {
String versionNo = matcher.group(1);
int version = Integer.valueOf(versionNo);
// 超过当前最大版本号或者低于最低的版本号均返回不匹配
if (version <= maxVersion && version >= this.version) {
return this;
}
}
return null;
}
// 如果找到了多个,那么需要按照优先级来进行匹配
@Override
public int compareTo(ApiVersionRequestCondition other, HttpServletRequest request) {
// 以版本号大小判定优先级,越高越优先
return other.version - this.version;
}
public int getVersion() {
return version;
}
public static void setMaxVersion(int maxVersion) {
ApiVersionRequestCondition.maxVersion = maxVersion;
}
}
因为默认的RequestMappingHandlerMapping
实现只有一个空的获取自定义RequestCondition的实现,所以需要继承实现:
public class ApiHandlerMapping extends RequestMappingHandlerMapping {
private int latestVersion = 1;
// 设置类上的匹配条件
@Override
protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
// 判断是否有@ApiVersion注解,构建基于@ApiVersion的RequestCondition
ApiVersionRequestCondition condition = buildFrom(AnnotationUtils.findAnnotation(handlerType, ApiVersion.class));
// 保存最大版本号
if (condition != null && condition.getVersion() > latestVersion) {
ApiVersionRequestCondition.setMaxVersion(condition.getVersion());
}
return condition;
}
// 设置方法上的匹配条件
@Override
protected RequestCondition<?> getCustomMethodCondition(Method method) {
// 判断是否有@ApiVersion注解,构建基于@ApiVersion的RequestCondition
ApiVersionRequestCondition condition = buildFrom(AnnotationUtils.findAnnotation(method, ApiVersion.class));
// 保存最大版本号
if (condition != null && condition.getVersion() > latestVersion) {
ApiVersionRequestCondition.setMaxVersion(condition.getVersion());
}
return condition;
}
private ApiVersionRequestCondition buildFrom(ApiVersion apiVersion) {
return apiVersion == null ? null : new ApiVersionRequestCondition(apiVersion.value());
}
}
在SpringBoot项目中增加Config,注入自定义的ApiHandlerMapping
:
@Configuration
public class Config extends WebMvcConfigurationSupport {
@Override
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
ApiHandlerMapping handlerMapping = new ApiHandlerMapping();
handlerMapping.setOrder(0);
handlerMapping.setInterceptors(getInterceptors());
return handlerMapping;
}
}
自定义Contoller测试:
@RestController
@ApiVersion
// 在url中增加一个占位符,用于匹配未知的版本 v1 v2...
@RequestMapping("/api/{version}")
public class Controller {
@GetMapping("/user/{id}")
@ApiVersion(2)
public Result<User> getUser(@PathVariable("id") String id) {
return new Result<>("0", "get user V2 :" + id, new User("user2_" + id, 20));
}
@GetMapping("/user/{id}")
@ApiVersion(4)
public Result<User> getUserV4(@PathVariable("id") String id) {
return new Result<>("0", "get user V4 :" + id, new User("user4_" + id, 20));
}
@GetMapping("/cat/{id}")
public Result<User> getCatV1(@PathVariable("id") String id) {
return new Result<>("0", "get cat V1 :" + id, new User("cat1_" + id, 20));
}
@GetMapping("/dog/{id}")
public Result<User> getDogV1(@PathVariable("id") String id) {
return new Result<>("0", "get dog V3 :" + id, new User("dog1_" + id, 20));
}
}
看下最终的Result定义:
// Result定义
public class Result<T> {
private String code;
private String msg;
private T data;
public Result() {
}
public Result(String code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
标签:getMatchingCondition,return,映射,匹配,SpringMVC,request,RequestMappingInfo,原理,null
From: https://www.cnblogs.com/likeguang/p/16725574.html