位置:org.springframework.util
�实现接口:org.springframework.util.PathMatcher
继承类:无
作用:获取到请求地址,可以对URLs字符串进行匹配

一、效果

规则:

  1. ?匹配一个字符
  2. *匹配0个或多个字符
  3. **匹配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

  1. /*
  2. 核心API
  3. 将给定路径与给定模式匹配
  4. 参数:
  5. pattern - 要匹配的模式
  6. path – 要测试的路径字符串
  7. fullMatch – 是否需要完整的模式匹配(否则,只要给定的基本路径就可以进行模式匹配就足够了)
  8. 返回:
  9. 如果提供的路径匹配,则返回true;否则,返回false
  10. */
  11. protected boolean doMatch(String pattern, String path, boolean fullMatch,
  12. @Nullable Map<String, String> uriTemplateVariables)
  13. // 一般匹配:antPathMatcher.match("/trip/api/*","/trip/api/x") >>> true
  14. public boolean match(String pattern, String path) {
  15. return doMatch(pattern, path, true, null);
  16. }
  17. // 完全路径匹配
  18. public boolean matchStart(String pattern, String path) {
  19. return doMatch(pattern, path, false, null);
  20. }

三、总结

AntPathMatcher提供了丰富的API,主要以doMatch为主。内部实现为匹配模式与匹配路径String数组的分词与遍历比较,并缺省启用缓存提高比较的性能。

四、补充

源码阅读参考: https://www.cnblogs.com/zhangxiaoguang/p/5855113.html