典型用法
基础用法
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {return "User ID: " + id;
}
请求:/users/1001
输出:User ID: 1001----
@GetMapping("/users/{userId}/orders/{orderId}")
public String getOrder(@PathVariable("userId") Long userId,@PathVariable("orderId") Long orderId) {return "User: " + userId + ", Order: " + orderId;
}
请求:/users/1001/orders/2002
输出:User: 1001, Order: 2002
路径变量与类型转换
Spring 自动进行类型转换(如 String → Integer、String → Long 等):
@GetMapping("/products/{id}")
public String getProduct(@PathVariable Integer id) {return "Product ID: " + id;
}
请求:/products/3003
输出:Product ID: 3003
使用 Map 接收所有路径变量
当不确定路径变量名称或需要动态处理时,可以使用 Map:
@GetMapping("/books/{category}/{bookId}")
public String getBookInfo(@PathVariable Map<String, String> pathVars) {return "Category: " + pathVars.get("category") + ", Book ID: " + pathVars.get("bookId");
}
请求:/books/fiction/978123
输出:Category: fiction, Book ID: 978123
路径变量不必须存在
Spring 的 @PathVariable 注解 默认要求路径变量必须存在,否则会抛出异常(如 NoHandlerFoundException)
@GetMapping("/posts/{id}")
public String getPost(@PathVariable Long id) {return "Post ID: " + id;
}请求 /posts/123 ✅ 正常
请求 /posts ❌ 报错:找不到匹配的路径
// ✅方法一:使用多个路径映射(推荐)
@GetMapping({"/posts", "/posts/{id}"})
public String getPost(@PathVariable(required = false) Long id) {if (id == null) {return "访问所有文章列表";}return "访问文章详情,ID: " + id;
}
请求 /posts → 输出:访问所有文章列表
请求 /posts/123 → 输出:访问文章详情,ID: 123// ✅方法二:使用 Optional(Spring 5.0+ 推荐)
@GetMapping({"/posts", "/posts/{id}"})
public String getPost(@PathVariable Optional<Long> id) {return id.map(i -> "访问文章详情,ID: " + i).orElse("访问所有文章列表");
}