在 Spring MVC 中,@RequestMapping("/hello") 与 @RequestMapping("hello/") 的区别主要体现在 URL 路径匹配规则 和 路径解析方式 上。以下是关键区别:
路径结构差异
@RequestMapping("/hello")
映射的是 绝对路径 /hello,即从应用根路径开始匹配。
例如:http://localhost:8080/your-app/hello
@RequestMapping("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/ 表示集合)。
示例对比
@Controller
public 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 默认不会将它们视为等价。