@RequestBody

时间:2015-07-28 15:34:38

标签: spring

我试图使用@InitBind注释来仅映射请求正文中对象的某些字段。

我有一个以这种方式定义的弹簧控制器:

@RequestMapping(value = "addAddress", method = RequestMethod.POST)
public Object addAddressToPerson(
        HttpServletRequest request,
        HttpServletResponse res,
        @RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "surname", required = false) String surname,
        @RequestBody personDTO personJson,BindingResult result) {

客户端请求将是一个代表personDTO的json,但出于安全原因,我不希望该字段除了要映射到对象中之外。

输入类似于:

{ "address":"123 Street","........}

personDTO包含许多字段,并且由于Spring将所有字段直接映射到DTO中,这可能是个问题。

我已经看到解决方案是使用Binder声明允许或禁止字段,但是如果我检查控制器内的personDTO,则会填充其他字段(例如,如果传递" id&# 34;:" 1234&#34)

任何提示?

活页夹代码如下:

    @InitBinder("orderJson")
protected void orderJsonBinder(WebDataBinder binder){
    binder.setAllowedFields(new String[]{"address"});
}

我错过了什么吗?

最诚挚的问候,

卢卡。

1 个答案:

答案 0 :(得分:3)

But you are not binding request parameters to a model attribute bean, you are just asking spring to use an appropriate MessageConverter to convert the request body. As you say it is Json, you will use a MappingJackson2HttpMessageConverter (or MappingJacksonHttpMessageConverter with Jackson 1.x). The Spring Reference Manual says for this converter :

[This is an] HttpMessageConverter implementation that can read and write JSON using Jackson's ObjectMapper. JSON mapping can be customized as needed through the use of Jackson's provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports (application/json).

@InitBinder can only configure binding of @ModelAttribute annotated parameters. It is useless here. If Jackson annotations are not enough, you will have to use a custom object mapper.

And I am surprised that you can use a BindingResult after a @RequestBody parameter, because the documentation says that it should follow a @ModelAttribute one.