Spring RestController:拒绝未知字段的请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring RestController:拒绝未知字段的请求相关的知识,希望对你有一定的参考价值。

我有以下端点:

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
public class TestController {

    @RequestMapping(value = "/persons", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<Integer> create(@RequestBody Person person) {
        // create person and return id
    }
}

今天如果我收到了这样一个未知领域的请求:

{
    "name" : "Pete",
    "bijsdf" : 51
}

我创造了这个人而忽略了未知领域。

如何检查是否存在未知字段然后返回错误请求?

答案

Spring(4.1.2-RELEASE)使用它的Jackson2ObjectMapperBuilder,默认情况下在过载jackson默认行为上禁用FAIL_ON_UNKNOWN_PROPERTIES。看到这个link配置弹簧。谢谢你的帮助

以上是关于Spring RestController:拒绝未知字段的请求的主要内容,如果未能解决你的问题,请参考以下文章