Spring 框架提供了一个名为 AntPathMatcher 的工具类,位于 org.springframework.util 包下。它在处理 URL 映射、权限校验等场景时非常实用,尤其是需要灵活匹配路径模式的时候。
基本使用
创建一个实例通常很简单,默认情况下它使用 / 作为路径分隔符。如果需要自定义分隔符,可以使用构造函数传入参数。
import org.springframework.util.AntPathMatcher;
public boolean hasUrl(String url) {
if (url == null || "".equals(url)) {
return false;
}
AntPathMatcher antPathMatcher = new AntPathMatcher();
// 定义匹配模式,支持通配符
String pattern = "/app/*.html";
if (antPathMatcher.match(pattern, url)) {
// 如果 URL 符合模式,返回 true
return true;
}
return false;
}
注意代码中的分号不能遗漏,这是新手容易忽略的细节。上面的示例展示了如何判断一个具体的 URL 是否符合给定的模式。
通配符规则
AntPathMatcher 的核心在于它的模糊匹配能力。通过在路径中添加 * 或 **,可以实现不同程度的替代。
| URL 路径 | 说明 |
|---|---|
/app/*.x | 匹配所有在 app 路径下的 .x 文件 |
/app/p?ttern | 匹配 /app/pattern 和 /app/pXttern,但不包括 /app/pttern |
/**/example | 匹配 /app/example, /app/foo/example, 和 /example |
/app/**/dir/file. |

