Spring Boot Controller 路径匹配规则
Spring Boot About 2,066 words配置文件
path_pattern_parser
是Spring5
中有引入的路径匹配规则,专用于SpringMVC
。
spring:
mvc:
pathmatch:
matching-strategy: path_pattern_parser
2.6.0 之前
默认是ant_path_matcher
解析方式。
// org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.Pathmatch
public static class Pathmatch {
private MatchingStrategy matchingStrategy;
private boolean useSuffixPattern;
private boolean useRegisteredSuffixPattern;
public Pathmatch() {
this.matchingStrategy = WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER;
this.useSuffixPattern = false;
this.useRegisteredSuffixPattern = false;
}
}
2.6.0 之后
默认是path_pattern_parser
解析方式。
// org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.Pathmatch
public static class Pathmatch {
private MatchingStrategy matchingStrategy;
private boolean useSuffixPattern;
private boolean useRegisteredSuffixPattern;
public Pathmatch() {
this.matchingStrategy = WebMvcProperties.MatchingStrategy.PATH_PATTERN_PARSER;
this.useSuffixPattern = false;
this.useRegisteredSuffixPattern = false;
}
}
差别
ant_path_matcher
- 通配符可以在中间,如:
abc/**/xyz
。
path_pattern_parser
- 通配符只能定义在尾部,如:
abc/xyz/**
。 - 可以使用
{*path}
接收多级路由。path
可以随意取名,与@PathVariable
名称对应即可。
{*path}
Spring Boot2.6.0
后支持。
定义{*path}
,使用@PathVariable String path
接收。
可以获取多级路径,没有{**path}
这种写法。
// Spring Boot2.6.0前会抛出以下错误
// Capturing patterns (*path) are not supported by the AntPathMatcher. Use the PathPatternParser instead.
// Spring Boot2.6.0后支持
@RequestMapping("/pass/{*path}")
public String pass(@PathVariable String path) {
System.out.println("pass#" + path);
return "pass#" + path;
}
接收一级路径
/*
可以接收一级路径。
@RequestMapping("/pass/*")
public String pass(HttpServletRequest request) {
System.out.println("pass#" + request.getServletPath());
return "pass#" + request.getServletPath();
}
接收多级路径
/**
可以接收多级路径。
@RequestMapping("/pass/**")
public String pass(HttpServletRequest request) {
System.out.println("pass#" + request.getServletPath());
return "pass#" + request.getServletPath();
}
Views: 6,951 · Posted: 2022-09-27
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...