4
我有一個Spring RestController,儘管在Chrome開發人員工具中看到正確的數據,但是任何嘗試發佈到它的嘗試都會返回400錯誤請求。 @Valid註釋正在踢出它,因爲ParameterDTO對象根本沒有被填充。Spring RestController POST 400錯誤請求
我的控制器
@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,雖然我的問題可能是有愛可信,但我使用郵差同樣的問題。我正在設置Content-Type和Accept標題。看起來Spring似乎並沒有對數據進行反序列化。
我認爲你缺少'@ RequestBody'之前'ParameterDTO parameterData'聲明 –
那不需要控制器被聲明爲@RestController,在Spring 4中添加之前需要RequestBody – greyfox
是的,這是必需的。什麼'@ RestController'給你的是'@ ResponseBody'邊界,而不是'@ RequestBody' –