Spring Boot 判断 URL 地址是否匹配 Controller 路径
Spring Boot About 2,160 wordsPathMatcher
match
方法第一个参数是Controller
的地址,第二个参数是需要匹配的URL
地址,可以是指定的字符串或者请求的地址。
@Controller
public class TestController {
@Resource
private PathMatcher pathMatcher;
@GetMapping("/")
public boolean match(HttpServletRequest request) {
boolean result = pathMatcher.match("/p/{id}.html", request.getRequestURI());
return result;
}
}
PathPatternParser
parse
方法接收Controller
的地址,matches
方法接收PathContainer
对象,PathContainer
对象的parsePath
方法接收需要匹配的URL
地址。
public class TestController {
@Resource
private PathPatternParser pathPatternParser;
@GetMapping("/")
public boolean match(HttpServletRequest request) {
boolean result = pathPatternParser.parse(Endpoint.Portal.POST).matches(PathContainer.parsePath(request.getRequestURI()));
return result;
}
}
源码
public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {
/**
* Return a global {@link PathMatcher} instance which is used for URL path
* matching with String patterns. The returned instance can be configured
* using {@link #configurePathMatch(PathMatchConfigurer)}.
* <p><b>Note:</b> This is only used when parsed patterns are not
* {@link PathMatchConfigurer#setPatternParser enabled}.
* @since 4.1
*/
@Bean
public PathMatcher mvcPathMatcher() {
return getPathMatchConfigurer().getPathMatcherOrDefault();
}
/**
* Return a global {@link PathPatternParser} instance to use for parsing
* patterns to match to the {@link org.springframework.http.server.RequestPath}.
* The returned instance can be configured using
* {@link #configurePathMatch(PathMatchConfigurer)}.
* @since 5.3.4
*/
@Bean
public PathPatternParser mvcPatternParser() {
return getPathMatchConfigurer().getPatternParserOrDefault();
}
}
public interface PathMatcher {
boolean match(String pattern, String path);
}
public class PathPatternParser {
public PathPattern parse(String pathPattern) throws PatternParseException {
return new InternalPathPatternParser(this).parse(pathPattern);
}
}
Views: 733 · Posted: 2024-03-29
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...