Spring RestController POST 400 Bad Request

I have a Spring RestController that any attempt to publish it returns 400 Bad Request, despite the correct data being sent to Chrome Developer Tools. The @Valid annotations push it out because the ParameterDTO is not populated at all.

My 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());
    }
}

I used axioms from JavaScript, and although my problem may be there, but I have the same problem as in Postman. I set the header to Content-Type and Accept. It seems like Spring is not deserializing the data at all.

enter image description here

enter image description here

+4
source share
1 answer

@RequestBody ParameterDTO parameterData, :

    @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();
    }
+5

Source: https://habr.com/ru/post/1670670/


All Articles