Spring的AntPathMatcher


本文的出现是为了能够分享个人所学的相关知识,检验自身学习成果。内容会和其他技术存在部分关联,如有任何描述错误或者说明有误的地方,还望各位指出。

1. 背景

在开发过程中,我们需要和url一样的匹配机制,spring为我们提供了AntPathMatcher.

2. 环境

JDK1.8

3. 介绍

Spring的AntPathMatcher源自Apache Ant.

3.1 常见语法

‘?’ 匹配一个字符(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”)

3.2 注意点

匹配文件路径时需要考虑无文件后缀名的情况
AntPathMatcher默认分隔符为’/‘可以自定义分隔符,在构造AntPathMather实例时注入。
AntPathMatcher 按照最长匹配规则进行匹配

4. 示例

java
public static void main(String[] args) {
        final AntPathMatcher antPathMatcher = new AntPathMatcher(":");
        String path = "root:parent:1";
        String pattern = "root:parent:*";
        System.out.println(antPathMatcher.match(pattern,path));
}