spring boot 31 restcontroller getmapping增加pathvariable
在Spring Boot 3.1中,可以通过在@RestController注解的方法中使用@GetMapping注解来定义RESTful API的GET请求。如果需要在API路径中包含动态参数,可以使用@PathVariable注解。
例如,假设我们有一个用户管理API,可以根据用户ID获取用户信息。我们可以定义如下的@RestController方法:
@RestController
public class UserController {
@GetMapping("/users/{userId}")
public User getUser(@PathVariable Long userId) {
// 根据userId查询用户信息
User user = userService.getUserById(userId);
return user;
}
}
在上面的代码中,我们使用@GetMapping注解来定义GET请求,同时使用@PathVariable注解来获取路径中的动态参数userId。
当客户端发送请求时,可以将具体的userId替换到路径中,例如:
GET /users/123
这个请求将会获取ID为123的用户信息。
注意,@PathVariable注解的值应该与路径中的参数名保持一致。例如,上面的例子中,我们使用@PathVariable Long userId来获取路径中的userId参数。如果路径中的参数名不是userId,那么@PathVariable注解的值应该调整为对应的参数名
原文地址: https://www.cveoy.top/t/topic/gtpG 著作权归作者所有。请勿转载和采集!