简体   繁体   中英

Spring Boot @GetMapping rule for multiple mapping

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;
        }
    }

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM