问题描述
杰克逊将null字符串反序列化为一个预期的空请求体(尽管能够关闭此行为会很好)。
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).
下面的代码在{}有效载荷的情况下触发验证,但在null有效载荷的情况下不触发验证。这迫使我再次检查null有效负载,这对我来说似乎不正常,因为PayloadValidator可能包含空检查本身。
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
}
- 有吗一般拒绝null @RequestBody的方法(即所有端点)?
- 如果没有,我可以在一个地方拥有所有验证逻辑并自动触发(即通过@Validated或@Valid)?
谢谢你,
伊曼纽尔
Thank you,Emanuel
推荐答案
@RequestBody
注释的属性
, true
默认情况下,所以带有空体的请求在这里不起作用,服务器应该响应HTTP 400错误。
The @RequestBody
annotation has an attribute required
which is true
by default, so request with an empty body should not work here and the server should respond with an HTTP 400 error.
In在这种情况下,null
有效负载实际上意味着请求正文不为空,并且Jackson将其反序列化为 null
价值。在这种情况下,我认为不会触发 @Validated
验证,这将使您了解当前的安排。
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.
正如您的问题所指出的那样,已经解决了这个问题。 Spring Framework 4.2 +。
As pointed out in your issue, this has been solved with SPR-13176 in Spring Framework 4.2+.
这篇关于Spring 4 - 拒绝“null” @RequestBody适用于所有端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!