1,当@PathVariable遇到/
常见的代码是如下图所示
@GetMapping("/hi1/{name}")
public String hello(@PathVariable String name){
return name;
}
如果假设我们的name字段含有/字符是,会怎么样呢,比如lcy/sss,lcysss/,/lcysss是回事什么样子呢?当我们尝试之后就会发现,lcy/sss这种的会报错页面不存在,其他的都会返回lcysss。针对这种情况,我们看一下为什么回事这样?
我们先连接一下url匹配执行方法的相关问题,大致代码过程参考org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#lookupHandlerMethod
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<>();
//尝试按照url进行精确匹配
List<T> directPathMatches = this.mappingRegistry.getMappingsByDirectPath(lookupPath);
if (directPathMatches != null) {
//精确匹配上,存储匹配结果
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
//如果没有匹配上,尝试根据请求来匹配
addMatchingMappings(this.mappingRegistry.getRegistrations().keySet(), matches, request);
}
if (!matches.isEmpty()) {
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
//处理多个匹配的结果
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
matches.sort(comparator);
bestMatch = matches.get(0);
if (logger.isTraceEnabled()) {
logger.trace(matches.size() + " matching mappings: " + matches);
}
if (CorsUtils.isPreFlightRequest(request)) {
for (Match match : matches) {
if (match.hasCorsConfig()) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
}
}
else {
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.getHandlerMethod().getMethod();
Method m2 = secondBestMatch.getHandlerMethod().getMethod();
String uri = request.getRequestURI();
throw new IllegalStateException(
"Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
}
}
}
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);
}
}
然后在仔细看第一步,根据path进行匹配查询
我们可以看到没有匹配上。
在上面没有精确匹配上,则开始执行模匹配,待匹配的方法可以参考如图:
显然。hi/{name}这个匹配方法已经出现了带匹配候选中,具体匹配的过程可以参考源码
org.springframework.web.servlet.mvc.method.RequestMappingInfo#getMatchingCondition
public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
//检查http请求方法是否预定义的方法条件匹配
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;
}
//代码检查请求的内容类型是否与定义的consumes条件匹配
ConsumesRequestCondition consumes = this.consumesCondition.getMatchingCondition(request);
if (consumes == null) {
return null;
}
//检查可接收的内容类型是否与定义的produces条件匹配
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;
}
}
//检查用户定义的任何自定义的模式条件匹配
RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
if (custom == null) {
return null;
}
return new RequestMappingInfo(this.name, pathPatterns, patterns,
methods, params, headers, consumes, produces, custom, this.options);
}
上述代码可以看到,匹配会查所有的的信息,如果有一个不匹配,则不符合
3.根据匹配情况返回结果
如果找到匹配的方法,则返回方法,如果没有,则返回null,同时为什么lcysss/,/lcysss没有报错,而是直接拿回了/。这里需要看一下匹配路径的方法:
org.springframework.web.servlet.mvc.condition.PatternsRequestCondition#getMatchingPatterns
public List<String> getMatchingPatterns(String lookupPath) { List<String> matches = null; for (String pattern : this.patterns) { String match = getMatchingPattern(pattern, lookupPath); if (match != null) { matches = (matches != null ? matches : new ArrayList<>()); matches.add(match); } } if (matches == null) { return Collections.emptyList(); } if (matches.size() > 1) { matches.sort(this.pathMatcher.getPatternComparator(lookupPath)); } return matches; }
private String getMatchingPattern(String pattern, String lookupPath) {
if (pattern.equals(lookupPath)) {
return pattern;
}
if (this.useSuffixPatternMatch) {
if (!this.fileExtensions.isEmpty() && lookupPath.indexOf('.') != -1) {
for (String extension : this.fileExtensions) {
if (this.pathMatcher.match(pattern + extension, lookupPath)) {
return pattern + extension;
}
}
}
else {
boolean hasSuffix = pattern.indexOf('.') != -1;
if (!hasSuffix && this.pathMatcher.match(pattern + ".*", lookupPath)) {
return pattern + ".*";
}
}
}
if (this.pathMatcher.match(pattern, lookupPath)) {
return pattern;
}
if (this.useTrailingSlashMatch) {
if (!pattern.endsWith("/") && this.pathMatcher.match(pattern + "/", lookupPath)) {
return pattern + "/";
}
}
return null;
}
最后会尝试加一下/进行匹配。