spring實現url路徑匹配

spring實現url路徑匹配

1,要想實現路徑匹配,我們需要藉助AntPathMatcher,這個是org.springframework.util工具包下的類。
2,AntPathMatcher不僅可以匹配Spring的@RequestMapping路徑,也可以用來匹配各種字符串,包括文件路徑等。

基本規則:

1,? 匹配一個字符(除過操作系統默認的文件分隔符)
2,* 匹配0個或多個字符
3,** 匹配0個或多個目錄
4,{spring:[a-z]+} 將正則表達式[a-z]+匹配到的值,賦值給名爲 spring 的路徑變量. (必須是完全匹配才行,在SpringMVC中只有完全匹配纔會進入controller層的方法)

注意事項:

1, 匹配文件路徑,需要匹配某目錄下及其各級子目錄下所有的文件,使用/**/而非.*,有些文件不一定有後綴
2,文件的分隔符,不同操作系統是不一樣的。一定要注意。

AntPathMatcher matcher = new AntPathMatcher(File.separator);
AntPathMatcher matcher = new AntPathMatcher(System.getProperty("file.separator"));

3,最長匹配規則(has more characters),即越精確的模式越會被優先匹配到。例如,URL請求/app/dir/file.jsp,現在存在兩個路徑匹配模式/**/.jsp和/app/dir/.jsp,那麼會根據模式/app/dir/*.jsp來匹配。

一些例子

assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.match("/**", "/testing/testing"));
assertTrue(pathMatcher.match("/?/a", "/a/a"));
assertTrue(pathMatcher.match("*.*", "test.test.test"));
發佈了25 篇原創文章 · 獲贊 13 · 訪問量 3904
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章