Spring RestController : reject request with unknown fields

余生长醉 提交于 2020-08-04 07:21:20

问题


I have the following endpoint :

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
    }
}

Today if I received a request with an unknown field like this :

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

I create the person and ignore the unknown field.

How can I check that there's an unknown field and then return a bad request ?


回答1:


Spring (4.1.2-RELEASE) use it's Jackson2ObjectMapperBuilder that by default disable FAIL_ON_UNKNOWN_PROPERTIES on overload jackson default behaviour. See this link to configure spring. Thx all for your helps



来源:https://stackoverflow.com/questions/29520853/spring-restcontroller-reject-request-with-unknown-fields

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