用于多个映射的 Spring Boot @GetMapping 规则

Man*_*nta 2 java request spring-boot get-mapping

我在控制器中有 3 种不同的方法来获取请求。

- 第一个通过 id 和路径变量获取用户:

@GetMapping(path="/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
Run Code Online (Sandbox Code Playgroud)

第二个根据username参数获取用户:

public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username)
Run Code Online (Sandbox Code Playgroud)

最后还有另一个让所有用户都获得的

public ResponseEntity<List<UserInfoDTO>> getAllUsers()
Run Code Online (Sandbox Code Playgroud)

@GetMapping第二种和第三种方法应该是什么?

例如@GetMapping对于所有用户和@GetMapping(path="/")按用户名的用户?

管他呢...

谢谢。

Vig*_*T I 5

定义映射完全取决于应用程序的上下文及其用例。

我们可以定义一个以用户为前缀的上下文,修改后的映射显示在下面的代码片段中,并且在调用时可以像注释中提到的那样调用它,

@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>
Run Code Online (Sandbox Code Playgroud)