You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何匹配@RequestMapping模式路径与真实请求路径并提取@PathVariable参数?

通用匹配@RequestMapping路径模式与真实请求路径的方法

直接用Spring框架自带的AntPathMatcher工具类就能解决,这正是Spring内部处理@RequestMapping路径匹配的核心实现,完全通用,不用自己写正则。

实现步骤

  • 确保项目引入了Spring核心依赖(Spring Boot项目默认已包含)
  • 使用AntPathMatcher的extractUriTemplateVariables方法,传入路径模式和真实请求路径,直接返回路径变量与对应值的Map

代码示例

import org.springframework.util.AntPathMatcher;
import java.util.Map;

public class PathMatcherExample {
    public static void main(String[] args) {
        // 初始化匹配器
        AntPathMatcher pathMatcher = new AntPathMatcher();
        
        // 你的@RequestMapping路径模式
        String pattern = "/customer/{id}/{whatever}";
        // 真实请求路径
        String actualPath = "/customer/1234/xyz";
        
        // 提取路径变量
        Map<String, String> pathVariables = pathMatcher.extractUriTemplateVariables(pattern, actualPath);
        
        // 获取对应值
        String id = pathVariables.get("id"); // 结果:1234
        String whatever = pathVariables.get("whatever"); // 结果:xyz
    }
}

额外说明

这个工具支持所有@RequestMapping支持的路径语法:

  • 带正则约束的路径变量,比如/customer/{id:[0-9]+},能正确提取符合规则的数值
  • 通配符*(匹配单层路径)、**(匹配多层路径)
  • 可选路径片段等

如果是在Spring容器环境中,还可以直接注入PathMatcher接口实例,无需手动初始化AntPathMatcher,Spring默认会提供该实现。

内容的提问来源于stack exchange,提问作者Datz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:31:15