gpt4 book ai didi

spring - @PathVariable 不与 @RequestBody 绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 09:32:31 24 4
gpt4 key购买 nike

当我不使用@RequestBody时,@PathVariable id会自动在我的Entity类中设置。但如果我使用 @RequestBody 则不然。我需要在 GenericValidator 执行验证之前设置 Entityid。为什么它在没有 @RequestBody 的情况下可以工作,而在使用它的情况下却不起作用?

实体类:

public class Entity {

private String id;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

//...

}

Controller 类:

@Controller
@RequestMapping(value = "/entity")
public class EntityController {

@Autowired
private GenericValidator validator;

@InitBinder
private void initBinder(WebDataBinder binder) {
binder.addValidators(validator);
}

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public @ResponseBody Response update(
@PathVariable String id,
@Valid @RequestBody Entity entity)
{
//...
}
}

最佳答案

单独使用时,@Valid 的工作方式与@ModelAttribute 非常相似。 Entity 方法参数将从模型中检索或实例化,WebDataBinder 将处理数据绑定(bind)过程(此时将设置 id),然后将进行验证。

@RequestBody 参数不像 @ModelAttribute 参数那样经历数据绑定(bind)过程。它们是通过 HttpMessageConverter 使用请求正文创建的,而不是将请求参数和路径变量的名称与对象字段的名称相匹配。与@Valid结合使用时,配置的验证器针对新对象运行,但仍然不会发生@ModelAttribute样式的数据绑定(bind)。

关于spring - @PathVariable 不与 @RequestBody 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19554958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com