spring boot中的AntPathMatcher匹配原則和含義


最近在使用spring security做登陸鑒權。登陸界面相關CSS和JS,以及部分api接口需要忽略,於是代碼中用到了anyMatchers。如下所示:

 1 @Override
 2     public void configure(WebSecurity web) throws Exception {
 3         // AuthenticationTokenFilter will ignore the below paths
 4         web
 5             .ignoring()
 6             .antMatchers(
 7                 HttpMethod.POST,
 8                 authenticationPath
 9             )
10 
11             // allow anonymous resource requests
12             .and()
13             .ignoring()
14             .antMatchers(
15                 HttpMethod.GET,
16                 "/",
17                 "/*.html",
18                 "/favicon.ico",
19                 "/**/*.html",
20                 "/**/*.css",
21                 "/**/*.js"
22             )
23 
24             // Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production)
25             .and()
26             .ignoring()
27             .antMatchers("/h2-console/**/**");
28     }

類似於正則的**或者*都表示什么含義呢?查詢了相關文檔,簡單的做一下總結,方便日后查詢。

  • ?匹配一個字符(matches one character)。
  • *  匹配0個或者多個字符 ( matches zero or more characters)。
  • ** 匹配url中的0個或多個子目錄 (matches zero or more directories in a path)
  • {spring:[a-z]+} 匹配滿足正則表達式[a-z]+的路徑,這些路徑賦值給變量"spring" (matches the regexp [a-z]+ as a path variable named "spring")

例子:

  • com/t?st.jsp  匹配com/test.jsp,也匹配com/tast.jsp或者com/txst.jsp (matches com/test.jsp but also com/tast.jsp or com/txst.jsp)
  • com/*.jsp  匹配com路徑下所有的.jsp文件。個人理解這里應該是直接包含的,不支持遞歸,比如com/good/*.jsp應該是匹配不上的。(matches all *.jsp files in the com directory)
  • com/**/test.jsp  匹配com路徑下所有的test.jsp文件。個人理解這里是支持遞歸的,表示com路徑下所有的test.jsp文件,例如:com/1/test.jsp, com/2/test.jsp, com/test.jsp 或者 com/java/1/test.jsp應該都可以匹配成功。(matches all test.jsp files underneath the com path)
  • org/springframework/**/*.jsp 匹配 org/springframework路徑下所有的jsp文件。(matches all .jsp files underneath the org/springframework path)
  • org/**/servlet/bla.jsp 匹配org/springframework/servlet/bla.jsp,同時也匹配 org/springframework/testing/servlet/bla.jsp和org/servlet/bla.jsp (matches org/springframework/servlet/bla.jsp but also org/springframework/testing/servlet/bla.jsp and org/servlet/bla.jsp)
  • com/{filename:\\w+}.jsp  匹配com/test.jsp 同時將"test"賦值給變量"filename"。(match com/test.jsp and assign the value "test" to the "filename" variable)

參考: 

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html 

https://www.w3schools.com/jsref/jsref_regexp_wordchar.asp 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM