Spring 4 - reject "null" @RequestBody for all endpoints

Jackson deserializes the null string as the body of the null query, which is expected (although it would be nice to disable this behavior).

The code below starts the check in case of payload "{}", but not in case of "zero" payload. This forces me to do another check for a zero payload, which does not seem normal to me, since PayloadValidator may include a zero check.

@InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(new PayloadValidator()); } @RequestMapping(method = POST, value = "/my/path/here") public ResponseEntity<String> create( @Validated @RequestBody Payload payload ) { if (payload == null) { // Payload validation logic not in one place } // useful work here } 
  • Is there a general way to reject null @RequestBody in general (i.e. for all endpoints)?
  • If not, can I have all the validation logic in one place and start automatically (i.e. via @Validated or @Valid)?

Thanks, Emanuel

+5
source share
1 answer

The @RequestBody has the required attribute, which is true by default, so a request with an empty body should not work here, and the server should respond with an HTTP 400 error.

In this case, the "null" payload effectively means that the request body is not null and that Jackson will deserialize it as null . In this case, I don’t think the @Validated check @Validated starting, which leaves you with your current layout.

As stated in your problem, this was resolved with SPR-13176 in Spring Framework 4.2+ .

+2
source

All Articles