antPathMatcher.match(pathPattern, antPath)
是 Spring 框架中 AntPathMatcher
类的一个方法,用于检查一个路径(antPath
)是否匹配某个模式(pathPattern
)。它是基于 Ant 风格的路径匹配规则实现的,广泛用于 Spring 的路径匹配场景,例如在 Spring MVC 的请求映射、Spring Security 的路径匹配以及 Spring Cloud Gateway 的路由规则中。
Ant 风格路径匹配规则
Ant 风格的路径模式支持以下几种通配符:
*
:匹配路径中的任意字符,但不跨目录。例如:- 模式
/api/*
匹配/api/abc
,但不匹配/api/abc/def
。
- 模式
**
:匹配路径中的任意字符,包括跨目录。例如:- 模式
/api/**
匹配/api/abc
和/api/abc/def
。
- 模式
?
:匹配路径中的任意单个字符。例如:- 模式
/api/a?c
匹配/api/abc
,但不匹配/api/ac
。
- 模式
{}
:用于路径变量。例如:- 模式
/api/users/{id}
可以匹配/api/users/123
,其中id
是路径变量。
- 模式
方法参数
pathPattern
:路径模式,即要匹配的规则。例如/api/**
或/api/users/{id}
。antPath
:实际的请求路径,即需要被匹配的路径。例如/api/users/123
或/api/abc
。
方法返回值
- 如果
antPath
匹配pathPattern
,则返回true
。 - 如果不匹配,则返回
false
。
示例
假设我们有以下代码:
AntPathMatcher antPathMatcher = new AntPathMatcher();
boolean result = antPathMatcher.match("/api/**", "/api/users/123");
- 模式
/api/**
表示匹配/api
下的所有路径。 - 实际路径
/api/users/123
显然符合这个模式,因此result
的值为true
。
再看另一个例子:
boolean result = antPathMatcher.match("/api/users/{id}", "/api/users/123");
- 模式
/api/users/{id}
表示匹配/api/users/
后面跟任意字符的路径。 - 实际路径
/api/users/123
也符合这个模式,因此result
的值为true
。
总结
antPathMatcher.match(pathPattern, antPath)
是一个非常强大的工具,用于基于模式匹配路径。它支持多种通配符,能够灵活地定义路径匹配规则,广泛应用于 Spring 框架中的路径匹配场景。