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

最近在使用spring security作登錄鑑權。登錄界面相關CSS和JS,以及部分api接口須要忽略,因而代碼中用到了anyMatchers。以下所示:css

 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     }

相似於正則的**或者*都表示什麼含義呢?查詢了相關文檔,簡單的作一下總結,方便往後查詢。html

  • ?匹配一個字符(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")

例子:java

  • 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)

參考: web

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html 正則表達式

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

相關文章
相關標籤/搜索