簡體   English   中英

Spring 引導@GetMapping規則進行多重映射

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM