1. 程式人生 > >spring工具類AntPathMatcher

spring工具類AntPathMatcher

  1. package cn.bidlink.wsmp.commons.security;

  2. import junit.framework.TestCase;

  3. import org.springframework.util.AntPathMatcher;

  4. import org.springframework.util.PathMatcher;

  5. public class AntPathMatcherTest extends TestCase {

  6. public void testMatch() {

  7. PathMatcher matcher = new AntPathMatcher();

  8. // 完全路徑url方式路徑匹配

  9. String requestPath="/user/list.htm?username=aaa&departmentid=2&pageNumber=1&pageSize=20";//請求路徑

  10. String patternPath="/user/list.htm**";//路徑匹配模式

  11. // 不完整路徑uri方式路徑匹配

  12. // String requestPath="/app/pub/login.do";//請求路徑

  13. // String patternPath="/**/login.do";//路徑匹配模式

  14. // 模糊路徑方式匹配

  15. // String requestPath="/app/pub/login.do";//請求路徑

  16. // String patternPath="/**/*.do";//路徑匹配模式

  17. // 包含模糊單字元路徑匹配

  18. //String requestPath = "/app/pub/login.do";// 請求路徑

  19. //String patternPath = "/**/lo?in.do";// 路徑匹配模式

  20. boolean result = matcher.match(patternPath, requestPath);

  21. assertTrue(result);

  22. }

  23. }

總結如下:

ANT方式的萬用字元有三種:

    ?(匹配任何單字元),*(匹配0或者任意數量的字元),**(匹配0或者更多的目錄)

url路徑匹配規則:

URL路徑 說明
/app/*.x 匹配(Matches)所有在app路徑下的.x檔案
/app/p?ttern 匹配(Matches) /app/pattern 和 /app/pXttern,但是不包括/app/pttern
/**/example 匹配(Matches) /app/example, /app/foo/example, 和 /example
/app/**/dir/file. 匹配(Matches) /app/dir/file.jsp, /app/foo/dir/file.html,/app/foo/bar/dir/file.pdf, 和 /app/dir/file.java
/**/*.jsp 匹配(Matches)任何的.jsp 檔案

最長匹配原則(has more characters) 說明,URL請求/app/dir/file.jsp,現在存在兩個路徑匹配模式/**/*.jsp和/app/dir/*.jsp,那麼會根據模式/app/dir/*.jsp來匹配