需求
在我们开发的中会遇到这样一种情况,在鉴权的时候,需要过滤掉白名单,例如:定义有这样一个url:good/detail/{id},需要判断uri是否能通过,传统的equals方法似乎有点难(PS:如果能用equals方法解决的请在评论区告诉我)
幸好spring提供了一个很好用的类,用于匹配
AntPathMatcher antPathMatcher = new AntPathMatcher();
// path路径是否符合pattern的规范
boolean match = antPathMatcher.match("/user/*", "/user/a");
System.out.println(match);
match = antPathMatcher.match("/user/**", "/user/a/b");
System.out.println(match);
match = antPathMatcher.match("/user/{id}", "/user/1"); System.out.println(match);
match = antPathMatcher.match("/user/name", "/user/a"); System.out.println(match);
boolean pattern = antPathMatcher.isPattern("user/{id}"); System.out.println(pattern);
// 匹配是不是以path打头的地址
boolean matchStart = antPathMatcher.matchStart("/1user/a", "/user"); System.out.println(matchStart);
// 对路径进行合并 --> /user/a/b
String combine = antPathMatcher.combine("/user", "a/b");
System.out.println(combine);
// 找出模糊匹配中 通过*或者? 匹配上的那一段配置
String extractPathWithinPattern = antPathMatcher.extractPathWithinPattern("/user/?", "/user/1");
System.out.println(extractPathWithinPattern);
// 找出模糊匹配中 找到匹配上的项 如果匹配规则和要匹配的项规则不一致 会报错
Map<String, String> extractUriTemplateVariables = antPathMatcher .extractUriTemplateVariables("{appName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar", "demo-sources-1.0.0.jar");
if (null != extractUriTemplateVariables) {
Iterator<String> iterator = extractUriTemplateVariables.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println("extractUriTemplateVariables:" + extractUriTemplateVariables.get(key));
}