参考地址: https://blog.csdn.net/yan_dk/article/details/7261059 https://www.jianshu.com/p/34f87d3097f5
在web应用中,需要对请求url路径进行一些判断匹配,完成一定的功能,如进行访问权限的判断,acegi就采用了路径匹配来判断请求url路径是否为合法,但是没有将api抽取出来,用起来还是依赖性太强,不好做轻量级的扩展。spring提供了工具类AntPathMatcher实现了判断路径匹配,非常简单好用,属轻量级的组件,下面具体谈一下。
先贴一段代码来快速了解一下它的用法(可以看一下代码注释,比较详细),如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public void testMatch() { PathMatcher matcher = new AntPathMatcher(); // 完全路径url方式路径匹配 // String requestPath="http://localhost:8080/pub/login.jsp";//请求路径 // String patternPath="**/login.jsp";//路径匹配模式 // 不完整路径uri方式路径匹配 // String requestPath="/app/pub/login.do";//请求路径 // String patternPath="/**/login.do";//路径匹配模式 // 模糊路径方式匹配 // String requestPath="/app/pub/login.do";//请求路径 // String patternPath="/**/*.do";//路径匹配模式 // 包含模糊单字符路径匹配 String requestPath = "/app/pub/login.do";//请求路径 String patternPath = "/**/lo?in.do";//路径匹配模式 boolean result = matcher.match(patternPath, requestPath); assertTrue(result); } |
注:以上代码取消注释的片段,都能通过测试,使用时可根据具体情况调整即可。
可以做URLs匹配,规则如下
?匹配一个字符
*匹配0个或多个字符
**匹配0个或多个目录
用例如下
/trip/api/*x 匹配 /trip/api/x,/trip/api/ax,/trip/api/abx ;但不匹配 /trip/abc/x;
/trip/a/a?x 匹配 /trip/a/abx;但不匹配 /trip/a/ax,/trip/a/abcx
/**/api/alie 匹配 /trip/api/alie,/trip/dax/api/alie;但不匹配 /trip/a/api
/**/*.htmlm 匹配所有以.htmlm结尾的路径