在 spring boot 中,使用 @pathvariable 将 url 路径中的占位符绑定到控制器方法的参数上。只需在方法签名中添加该注解并指定变量名,spring mvc 会自动解析请求路径并注入值。

@PathVariable 如何映射路径片段
通过定义包含花括号的 URL 模式(如 /users/{id}),并在方法参数上使用 @PathVariable("id"),可以将路径中的动态部分提取为字符串或基本类型。

import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{userId}")
public String getUser(@PathVariable Long userId) {
return "Fetching user with ID: " + userId;
}
}
如何处理可选的路径变量
默认情况下,路径变量是必需的。如果希望路径变量变为可选,可以设置 required = false,此时若路径中缺少该部分,参数值为 null。

import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/items")
public class ItemController {
@GetMapping("/{itemId}/details")
public String getItemDetails(
@PathVariable Long itemId,
@PathVariable(required = false) String format) {
if (format == null) {
return "Standard details for item: " + itemId;
}
return format.toUpperCase() + " details for item: " + itemId;
}
}
当路径变量命名与参数不一致时会发生什么
如果 URL 中的变量名与方法参数名不同,必须显式指定 @PathVariable 的值,否则 Spring 会抛出 MissingPathVariableException。











