![](/img/trans.png)
[英]Mapping two @GetMapping to same @RestController into Spring Boot
[英]Spring Boot @GetMapping rule for multiple mapping
我在 controller 中有 3 种不同的方法来获取请求。
- 第一个使用路径变量通过 id 获取用户:
@GetMapping(path="/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
第二个根据username
参数获取用户:
public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username)
最后是另一个让所有用户
public ResponseEntity<List<UserInfoDTO>> getAllUsers()
第二种和第三种方法的@GetMapping
应该是什么?
例如, @GetMapping
用于所有用户, @GetMapping(path="/")
用于用户名?
管他呢...
谢谢。
例如,可选的username
参数:
@GetMapping(path = "/")
public ResponseEntity<?> getUserByUsername(@RequestParam(required = false) final String username) {
if (username != null) {
// http://localhost:8080/?username=myname
return new ResponseEntity<>(new UserInfoDTO("by username: " + username), HttpStatus.OK);
} else {
// http://localhost:8080/
return getAllUsers();
}
}
private ResponseEntity<List<UserInfoDTO>> getAllUsers() {
return new ResponseEntity<>(List.of(new UserInfoDTO("user1-of-all"), new UserInfoDTO("user2-of-all")),
HttpStatus.OK);
}
public static class UserInfoDTO {
public UserInfoDTO(final String name) {
this.name = name;
}
private final String name;
public String getName() {
return name;
}
}
定义映射完全取决于您的应用程序及其用例的上下文。
我们可以定义一个以用户为前缀的上下文,修改后的映射显示在下面的代码片段中,在调用时可以像评论中提到的那样调用它,
@GetMapping(path="/users/")
public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username) {
}
// GET: <protocol>://<hostUrl>/users?username=<username>
@GetMapping(path="/users")
public ResponseEntity<List<UserInfoDTO>> getAllUsers() {
}
// GET: <protocol>://<hostUrl>/users
@GetMapping(path="/users/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
// GET: <protocol>://<hostUrl>/users/<userid>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.