简体   繁体   中英

Spring RestController POST 400 Bad Request

I have a Spring RestController that any attempt to post to it returns 400 Bad Request despite seeing the correct data being sent in Chrome Developer Tools. The @Valid annotation is kicking it out because the ParameterDTO object is not being 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 was using axios from JavaScript and though my problem might be there but I have the same issue using Postman. I am setting the Content-Type and Accept header. It seems like Spring is not deserializing the data at all.

在此输入图像描述

在此输入图像描述

You need to add @RequestBody annotation before ParameterDTO parameterData declaration, like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM