Spring 4 - reject “null” @RequestBody for all endpoints

放肆的年华 提交于 2019-12-12 11:10:15

问题


Jackson deserializes the "null" string as a null request body which is expected (although it would be nice to be able to switch this behaviour off).

The code below triggers validation in case of "{}" payload but not in case of "null" payload. This forces me to do another check for null payload which doesn't seem normal to me since the PayloadValidator could include the null check itself.

@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
}
  1. Is there a generic way of rejecting null @RequestBody altogether (i.e. for all endpoints)?
  2. If not, can I have all the validation logic in one place and be automatically triggered (i.e. via @Validated or @Valid)?

Thank you, Emanuel


回答1:


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

In this case, a "null" payload effectively means that the request body is not null and that Jackson will deserialize it as a null value. In this case, I don't think that the @Validated validation is triggered, which leaves you with your current arrangement.

As pointed out in your issue, this has been solved with SPR-13176 in Spring Framework 4.2+.



来源:https://stackoverflow.com/questions/32222099/spring-4-reject-null-requestbody-for-all-endpoints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!