Spring 之 AntPathMatcher類


Spring 之 AntPathMatcher類

 

 

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

1、簡介

SpringMVC的路徑匹配規則是依照Ant的來的,實際上不只是SpringMVC,整個Spring框架的路徑解析都是按照Ant的風格來的;

AntPathMatcher不僅可以匹配Spring的@RequestMapping路徑,也可以用來匹配各種字符串,包括文件路徑等。

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

2、使用示例

public class AntTest { public static void main(String[] args) { antPathMatcher(); } public static void antPathMatcher() { AntPathMatcher antPathMatcher = new AntPathMatcher(); // path路徑是否符合pattern的規范
        boolean match = antPathMatcher.match("/user/*", "/user/a"); System.out.println(match); // true
        match = antPathMatcher.match("/user/**", "/user/a/b"); System.out.println(match); // true
        match = antPathMatcher.match("/user/{id}", "/user/1"); System.out.println(match); // true
        match = antPathMatcher.match("/user/name", "/user/a"); System.out.println(match); // false // 是否有模糊匹配
        boolean pattern = antPathMatcher.isPattern("user/{id}"); System.out.println(pattern); // true // 匹配是不是以path打頭的地址
        boolean matchStart = antPathMatcher.matchStart("/1user/a", "/user"); System.out.println(matchStart); // false // 對路徑進行合並 --> /user/a/b
        String combine = antPathMatcher.combine("/user", "a/b"); System.out.println(combine); // /user/a/b // 找出模糊匹配中 通過*或者? 匹配上的那一段配置
        String extractPathWithinPattern = antPathMatcher.extractPathWithinPattern("/user/?", "/user/1"); System.out.println(extractPathWithinPattern); // 1 // 找出模糊匹配中 找到匹配上的項 如果匹配規則和要匹配的項規則不一致 會報錯
        Map<String, String> extractUriTemplateVariables = antPathMatcher .extractUriTemplateVariables("{appName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar", "demo-sources-1.0.0.jar"); if (null != extractUriTemplateVariables) { Iterator<String> iterator = extractUriTemplateVariables.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); // extractUriTemplateVariables:demo // extractUriTemplateVariables:1.0.0
                System.out.println("extractUriTemplateVariables:" + extractUriTemplateVariables.get(key)); } } } }

 

注意事項:

匹配文件路徑,需要匹配某目錄下及其各級子目錄下所有的文件,使用/**/*而非*.*,因為有的文件不一定含有文件后綴;

 


免責聲明!

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



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