gpt4 book ai didi

java - Spring RestController POST 400 错误请求

转载 作者:搜寻专家 更新时间:2023-11-01 02:21:04 32 4
gpt4 key购买 nike

我有一个 Spring RestController,尽管在 Chrome Developer Tools 中看到发送的数据正确,但任何向其发布的尝试都会返回 400 Bad Request。 @Valid 注释将其踢出,因为根本没有填充 ParameterDTO 对象。

我的 Controller

@RestController
@RequestMapping(path = "/api/parameters", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public class ParameterResource {

private final ParameterService parameterService;

@Autowired
public ParameterResource(ParameterService parameterService) {
this.parameterService = parameterService;
}

@GetMapping
public ResponseEntity<?> getParameters(@RequestParam(value = "subGroupId", required = false) Integer subGroupId) {
if (subGroupId != null) {
return ResponseEntity.ok(parameterService.getParameters(subGroupId));
}
return ResponseEntity.ok(parameterService.getParameters());
}

@PostMapping
public ResponseEntity<?> createParameter(@Valid ParameterDTO parameterData) {
int id = parameterService.saveParameter(parameterData);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(id).toUri();
return ResponseEntity.created(uri).build();
}

@GetMapping(path = "/levels")
public ResponseEntity<?> getParameterLevels() {
return ResponseEntity.ok(ParameterLevels.getParameterLevelMap());
}

@GetMapping(path = "/levels/{id}/values")
public ResponseEntity<?> getLevelValues(@PathVariable("id") int levelId) {
return ResponseEntity.ok(parameterService.getParameterLevelValues(levelId));
}

@GetMapping(path = "/types")
public ResponseEntity<?> getParameterTypes() {
return ResponseEntity.ok(parameterService.getParameterTypes());
}
}

我在 JavaScript 中使用 axios,虽然我的问题可能存在,但我在使用 Postman 时遇到了同样的问题。我正在设置 Content-Type 和 Accept header 。似乎 Spring 根本没有反序列化数据。

enter image description here

enter image description here

最佳答案

需要在ParameterDTO parameterData声明之前添加@RequestBody注解,如下所示:

    @PostMapping
public ResponseEntity<?> createParameter(@RequestBody @Valid ParameterDTO parameterData) {
int id = parameterService.saveParameter(parameterData);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(id).toUri();
return ResponseEntity.created(uri).build();
}

关于java - Spring RestController POST 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424977/

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