I have 3 different method in controller for get requests.
-the 1st one to get a user by id with a path variable:
@GetMapping(path="/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
The 2nd gets a user based on the username
parameter:
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?
For exemple @GetMapping
for all users and @GetMapping(path="/")
for a user by username?
Or whatever...
Thanks.
For example, optional username
param:
@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;
}
}