REST如何在没有完整实体(@RequestBody)的情况下进行POST或PUT操作

问题描述 投票:0回答:2

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

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

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

/votes

并且如果有更新:

/votes/{id}

大概我应该这样从前端收到我控制器中的全票实体:

@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/1?restaurantId=10
java rest post uri put
2个回答
0
投票

您应该将其更改为:

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

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


0
投票

为什么不使用路径参数?将get参数传递到POST和PUT有点奇怪。

@PostMapping("/{restaurantId}")
public void createPost(@NonNull @PathVariable(value = "restaurantId") String restaurantId) {
    voteService.create(SecurityUtil.getUserId(), restaurantId);
}

@PutMapping("/{restaurantId}")
public void createPut(@NonNull @PathVariable(value = "restaurantId") String restaurantId) {
    voteService.create(SecurityUtil.getUserId(), restaurantId);
}
© www.soinside.com 2019 - 2024. All rights reserved.