Skip to content

路径参数

Spring Boot(Spring MVC) 中,获取 URL 路径参数(Path Variable) 通常使用 @PathVariable 注解。

单个路径参数

URL:

GET /user/100

Controller:

java
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/{id}")
    public String getUser(@PathVariable("id") Integer id) {
        return "用户ID:" + id;
    }

}

多个路径参数

URL:

/order/10/user/100

Controller:

java
@GetMapping("/order/{orderId}/user/{userId}")
public String getOrder(
        @PathVariable Integer orderId,
        @PathVariable Integer userId) {

    return "orderId=" + orderId + ", userId=" + userId;
}

省略参数名

如果 参数名和路径变量名一致,可以省略:

java
@GetMapping("/product/{id}")
public String getProduct(@PathVariable Integer id) {
    return "productId=" + id;
}

获取所有路径参数

java
@GetMapping("/test/{a}/{b}")
public Map<String, String> test(@PathVariable Map<String,String> map){
    return map;
}