spring实现url路径匹配
1,要想实现路径匹配,我们需要借助AntPathMatcher,这个是org.springframework.util工具包下的类。
2,AntPathMatcher不仅可以匹配Spring的@RequestMapping路径,也可以用来匹配各种字符串,包括文件路径等。
基本规则:
1,? 匹配一个字符(除过操作系统默认的文件分隔符)
2,* 匹配0个或多个字符
3,** 匹配0个或多个目录
4,{spring:[a-z]+} 将正则表达式[a-z]+匹配到的值,赋值给名为 spring 的路径变量. (必须是完全匹配才行,在SpringMVC中只有完全匹配才会进入controller层的方法)
注意事项:
1, 匹配文件路径,需要匹配某目录下及其各级子目录下所有的文件,使用/**/而非.*,有些文件不一定有后缀
2,文件的分隔符,不同操作系统是不一样的。一定要注意。
AntPathMatcher matcher = new AntPathMatcher(File.separator);
AntPathMatcher matcher = new AntPathMatcher(System.getProperty("file.separator"));
3,最长匹配规则(has more characters),即越精确的模式越会被优先匹配到。例如,URL请求/app/dir/file.jsp,现在存在两个路径匹配模式/**/.jsp和/app/dir/.jsp,那么会根据模式/app/dir/*.jsp来匹配。
一些例子
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.match("/**", "/testing/testing"));
assertTrue(pathMatcher.match("/?/a", "/a/a"));
assertTrue(pathMatcher.match("*.*", "test.test.test"));