[英]Spring Boot @GetMapping rule for multiple mapping
I have 3 different method in controller for get requests.我在 controller 中有 3 种不同的方法来获取请求。
-the 1st one to get a user by id with a path variable: - 第一个使用路径变量通过 id 获取用户:
@GetMapping(path="/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
The 2nd gets a user based on the username
parameter:第二个根据
username
参数获取用户:
public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username)
And finally another one to get all users最后是另一个让所有用户
public ResponseEntity<List<UserInfoDTO>> getAllUsers()
What should be the @GetMapping
for the 2nd and 3rd method?第二种和第三种方法的
@GetMapping
应该是什么?
For exemple @GetMapping
for all users and @GetMapping(path="/")
for a user by username?例如,
@GetMapping
用于所有用户, @GetMapping(path="/")
用于用户名?
Or whatever...管他呢...
Thanks.谢谢。
For example, optional username
param:例如,可选的
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;
}
}
Defining the Mappings purely depends on the context of your application and its usecases.定义映射完全取决于您的应用程序及其用例的上下文。
We can define a context prefixed by users and modified mappings are show in the snippet below and at the time of invocation it can be called like mentioned in the comments,我们可以定义一个以用户为前缀的上下文,修改后的映射显示在下面的代码片段中,在调用时可以像评论中提到的那样调用它,
@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.