gpt4 book ai didi

java - REST 如何在没有完整实体的情况下 POST 或 PUT (@RequestBody)

转载 作者:行者123 更新时间:2023-12-01 16:51:31 25 4
gpt4 key购买 nike

我有一个包含字段的实体“投票”:

private Integer id;
private LocalDate date;
private LocalTime time = LocalTime.now();
private User user;
private Restaurant restaurant;

我知道对于 REST POST 最好我应该使用这样的资源模式:

/votes

如果更新:

/votes/{voteId}

大概我应该从前端收到 Controller 中的完整投票实体,如下所示:

@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Vote> create(@RequestBody Vote vote)

但我不需要它来创建或更新该实体,我只需要这样的restaurantId:

@PostMapping
public void create(@RequestParam int restaurantId) {
voteService.create(SecurityUtil.getUserId(), restaurantId);
}

那么,使用这样的资源模式是正确的选择,还是我错了?

对于 POST 创建:

/votes?restaurantId=10

对于 PUT 更新:

/votes/{voteId}?restaurantId=10

最佳答案

您应该将其更改为:

@PostMapping
public void create(@RequestParam("restaurantId") int restaurantId) {
voteService.create(SecurityUtil.getUserId(), restaurantId);
}

您应该在 @RequestParam("param_name") 中提及参数名称

关于java - REST 如何在没有完整实体的情况下 POST 或 PUT (@RequestBody),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61676624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com