SpringMVC中自动匹配请求路径时,默认情况下会自动匹配”.*”的请求,
比如如果请求为“helloword”,方法中匹配路径设置如下:
@RequestMapping(value = "helloword", method = RequestMethod.POST)
但是如果你将请求修改为“helloword.123”仍然会匹配成功,并进去方法执行。
这是因为在springMVC中默认会对不加”.”的请求增加”.*”
源码如下:
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 + ".*";
}
}
}
从源码可以看到,this.useSuffixPatternMatch默认为true,也就是会增加模糊匹配。
可以通过设置RequestMappingHandlerMapping的useSuffixPatternMatch为false来禁止自动匹配
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useSuffixPatternMatch" value="false"/>
</bean>