Srping:@RequestMapping中“/“
在 Spring MVC 中RequestMapping(/hello) 与 RequestMapping(hello/) 的区别主要体现在 URL 路径匹配规则 和 路径解析方式 上。以下是关键区别路径结构差异RequestMapping(/hello)映射的是 绝对路径 /hello即从应用根路径开始匹配。例如http://localhost:8080/your-app/helloRequestMapping(hello/)映射的是 相对路径 hello/其实际匹配路径取决于当前类或上下文的父路径。如果该注解写在类上如 RequestMapping(/api)则最终路径为 /api/hello/如果写在方法上且类无前缀则路径为 /hello/注意末尾多一个 /。实际访问行为/hello可通过 http://localhost:8080/.../hello 正常访问。hello/路径末尾包含 /因此http://localhost:8080/.../hello/ ✅ 可访问http://localhost:8080/.../hello ❌ 通常 404除非 Spring 配置了自动重定向或路径规范化。Spring 默认 不自动重定向 缺少尾部斜杠的请求。若路径定义为 hello/访问 /hello 会因路径不匹配而失败 。最佳实践建议推荐使用带前导斜杠的形式RequestMapping(/hello)这是标准写法语义清晰避免歧义 。避免在路径末尾随意添加 /除非明确需要区分带/与不带/的资源如 RESTful 设计中 /users/ 表示集合。示例对比Controllerpublic class TestController {// 只能通过 /hello 访问RequestMapping(/hello)public String handleHello() {return hello;}// 只能通过 /hello/ 访问注意末尾斜杠RequestMapping(hello/)public String handleHelloWithSlash() {return helloWithSlash;}}GET /hello → 匹配第一个方法GET /hello/ → 匹配第二个方法GET /hello 访问第二个方法 → 404 Not Found综上/hello 与 hello/ 在路径上是不同的前者是精确路径后者是带尾部斜杠的路径Spring 默认不会将它们视为等价。