Spring 之 AntPathMatcher类
1、简介
SpringMVC的路径匹配规则是依照Ant的来的,实际上不只是SpringMVC,整个Spring框架的路径解析都是按照Ant的风格来的;
AntPathMatcher不仅可以匹配Spring的@RequestMapping路径,也可以用来匹配各种字符串,包括文件路径等。
(1)? 匹配一个字符(除过操作系统默认的文件分隔符)
(2)* 匹配0个或多个字符
(3)**匹配0个或多个目录
(4){spring:[a-z]+} 将正则表达式[a-z]+匹配到的值,赋值给名为 spring 的路径变量.
(PS:必须是完全匹配才行,在SpringMVC中只有完全匹配才会进入controller层的方法)
2、使用示例
public class AntTest { public static void main(String[] args) { antPathMatcher(); } public static void antPathMatcher() { AntPathMatcher antPathMatcher = new AntPathMatcher(); // path路径是否符合pattern的规范
boolean match = antPathMatcher.match("/user/*", "/user/a"); System.out.println(match); // true
match = antPathMatcher.match("/user/**", "/user/a/b"); System.out.println(match); // true
match = antPathMatcher.match("/user/{id}", "/user/1"); System.out.println(match); // true
match = antPathMatcher.match("/user/name", "/user/a"); System.out.println(match); // false // 是否有模糊匹配
boolean pattern = antPathMatcher.isPattern("user/{id}"); System.out.println(pattern); // true // 匹配是不是以path打头的地址
boolean matchStart = antPathMatcher.matchStart("/1user/a", "/user"); System.out.println(matchStart); // false // 对路径进行合并 --> /user/a/b
String combine = antPathMatcher.combine("/user", "a/b"); System.out.println(combine); // /user/a/b // 找出模糊匹配中 通过*或者? 匹配上的那一段配置
String extractPathWithinPattern = antPathMatcher.extractPathWithinPattern("/user/?", "/user/1"); System.out.println(extractPathWithinPattern); // 1 // 找出模糊匹配中 找到匹配上的项 如果匹配规则和要匹配的项规则不一致 会报错
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(); // extractUriTemplateVariables:demo // extractUriTemplateVariables:1.0.0
System.out.println("extractUriTemplateVariables:" + extractUriTemplateVariables.get(key)); } } } }
注意事项:
匹配文件路径,需要匹配某目录下及其各级子目录下所有的文件,使用/**/*而非*.*,因为有的文件不一定含有文件后缀;