位置:org.springframework.util
�实现接口:org.springframework.util.PathMatcher
继承类:无
作用:获取到请求地址,可以对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结尾的路径
最长匹配原则(has more characters):URL请求/app/dir/file.jsp,现在存在两个路径匹配模式/*/.jsp和/app/dir/.jsp,那么会根据模式/app/dir/.jsp来匹配
二、API
/*
核心API
将给定路径与给定模式匹配
参数:
pattern - 要匹配的模式
path – 要测试的路径字符串
fullMatch – 是否需要完整的模式匹配(否则,只要给定的基本路径就可以进行模式匹配就足够了)
返回:
如果提供的路径匹配,则返回true;否则,返回false
*/
protected boolean doMatch(String pattern, String path, boolean fullMatch,
@Nullable Map<String, String> uriTemplateVariables)
// 一般匹配:antPathMatcher.match("/trip/api/*","/trip/api/x") >>> true
public boolean match(String pattern, String path) {
return doMatch(pattern, path, true, null);
}
// 完全路径匹配
public boolean matchStart(String pattern, String path) {
return doMatch(pattern, path, false, null);
}
三、总结
AntPathMatcher提供了丰富的API,主要以doMatch为主。内部实现为匹配模式与匹配路径String数组的分词与遍历比较,并缺省启用缓存提高比较的性能。
四、补充
源码阅读参考: https://www.cnblogs.com/zhangxiaoguang/p/5855113.html
�