英文:
Multiple endpoints with the same path but with different @RequestParam values
问题
我有一个API路径 GET /users/copy
。我可以有两个使用相同 /users/type
路径但使用不同的RequestParams集合的API,使用以下结构:
@GetMapping(value = "/users/copy", params = {"type"})
public ResponseEntity<UserDto> copyUserWithType(@RequestParam UserTypeEnum type) {
...
}
@GetMapping(value = "/users/copy", params = {"origin"})
public ResponseEntity<UserDto> copyUserWithOrigin(@RequestParam UserOriginEnum origin) {
...
}
但是 如果我需要为不同的用户类型(例如 type = OLD
和 type = NEW
)拥有不同的API,是否仍然可以为它们使用相同的 GET /users/copy
路径呢?
也许可以像这样:
@GetMapping(value = "/users/copy", params = {"type=OLD"})
public ResponseEntity<UserDto> copyUserWithTypeOld(@RequestParam UserTypeEnum type) {
...
}
@GetMapping(value = "/users/copy", params = {"type=NEW"})
public ResponseEntity<UserDto> copyUserWithTypeNew(@RequestParam UserTypeEnum type) {
...
}
英文:
I have an API path GET /users/copy
. I can have two APIs with the same /users/type
path but with different sets of RequestParams using the following construction:
@GetMapping(value = "/users/copy", params = {"type"})
public ResponseEntity<UserDto> copyUserWithType(@RequestParam UserTypeEnum type) {
...
}
@GetMapping(value = "/users/copy", params = {"origin"})
public ResponseEntity<UserDto> copyUserWithOrigin(@RequestParam UserOriginEnum origin) {
...
}
BUT in case I need to have different APIs for different user types (like for type = OLD
and type = NEW
), is there a way to still have the same GET /users/copy
path for them?
Perhaps something like:
@GetMapping(value = "/users/copy", params = {"type=OLD"})
public ResponseEntity<UserDto> copyUserWithTypeOld(@RequestParam UserTypeEnum type) {
...
}
@GetMapping(value = "/users/copy", params = {"type=NEW"})
public ResponseEntity<UserDto> copyUserWithTypeNew(@RequestParam UserTypeEnum type) {
...
}
答案1
得分: 0
实际上,答案就在问题中。
为了在具有相同路径和相同一组 @RequestParam 的不同 API 端点之间实现,但具有不同的 @RequestParam 值,您需要按以下方式指定 params
属性:
@GetMapping(value = "/users/copy", params = {"type=OLD"})
public ResponseEntity<UserDto> copyUserWithTypeOld(@RequestParam UserTypeEnum type) {
...
}
@GetMapping(value = "/users/copy", params = {"type=NEW"})
public ResponseEntity<UserDto> copyUserWithTypeNew(@RequestParam UserTypeEnum type) {
...
}
英文:
Actually, the answer was in the question.
In order to have different APIs endpoints with the same path and the same set of @RequestParam, but with different @RequestParam values you need to specify params
attribute as such:
@GetMapping(value = "/users/copy", params = {"type=OLD"})
public ResponseEntity<UserDto> copyUserWithTypeOld(@RequestParam UserTypeEnum type) {
...
}
@GetMapping(value = "/users/copy", params = {"type=NEW"})
public ResponseEntity<UserDto> copyUserWithTypeNew(@RequestParam UserTypeEnum type) {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论