在翻阅源码的时候,在请求接口URI匹配的地方看到了一个眼熟的工具类-AntPathMatcher,借着这个功夫,做个小笔记
AntPathMatcher前言
(1)SpringMVC的路径匹配规则是依照Ant的来的,实际上不只是SpringMVC,整个Spring框架的路径解析都是按照Ant的风格来的;
(2)AntPathMatcher不仅可以匹配Spring的@RequestMapping路径,也可以用来匹配各种字符串,包括文件路径等。
基本规则
(1)? 匹配一个字符(除过操作系统默认的文件分隔符)
(2)* 匹配0个或多个字符
(3)**匹配0个或多个目录
(4){spring:[a-z]+} 将正则表达式[a-z]+匹配到的值,赋值给名为 spring 的路径变量.
注意事项
(1)匹配文件路径,需要匹配某目录下及其各级子目录下所有的文件,使用/**/*而非*.*,因为有的文件不一定含有文件后缀;
(2)匹配文件路径,使用AntPathMatcher创建一个对象时,需要注意AntPathMatcher也有有参构造,传递路径分隔符参数pathSeparator,对于文件路径的匹配来说,则需要根据不同的操作系统来传递各自的文件分隔符,以此防止匹配文件路径错误。
(3)最长匹配规则(has more characters),即越精确的模式越会被优先匹配到。例如,URL请求/app/dir/file.jsp,现在存在两个路径匹配模式/**/*.jsp和/app/dir/*.jsp,那么会根据模式/app/dir/*.jsp来匹配。
使用方法
//spring mvc模式
AntPathMatcher pathMatcher = new AntPathMatcher();
//文件目录模式
AntPathMatcher matcher = new AntPathMatcher(File.separator);
AntPathMatcher matcher = new AntPathMatcher(System.getProperty("file.separator"));
测试用例
// 字符串完全匹配
Assert.isTrue(pathMatcher.match("test", "test"));
Assert.isTrue(pathMatcher.match("/test", "/test"));
Assert.isTrue(!pathMatcher.match("/test", "test"));
// ?通配符匹配
Assert.isTrue(pathMatcher.match("t?st", "test"));
Assert.isTrue(pathMatcher.match("??st", "test"));
Assert.isTrue(!pathMatcher.match("tes?", "testt"));
// *通配符匹配
Assert.isTrue(pathMatcher.match("/*", "/test"));
Assert.isTrue(pathMatcher.match("/test*", "/test"));
Assert.isTrue(pathMatcher.match("*.*", "test.test.test"));
Assert.isTrue(!pathMatcher.match("/test/*", "/test/test/test"));
Assert.isTrue(!pathMatcher.match("test/*", "test"));
// **通配符匹配
Assert.isTrue(pathMatcher.match("/**", "/testing/testing"));
Assert.isTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla"));
Assert.isTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla"));
// {}模式匹配
Assert.isTrue(pathMatcher.match("/student/{name}", "/student/zhangsan"));
Assert.isTrue(!pathMatcher.match("/student/{id:[0-9]*}", "/student/zhangsan"));
Assert.isTrue(pathMatcher.match("/student/{id:[0-9]*}", "/student/214"));
使用场景
在需要针对某些url进行特过滤或殊处理的情况下,可以在过滤器或拦截器等进行匹配操作