Mas*_*ode 8 spring spring-mvc spring-boot
如果我使用@InitBinder而不限制它,它可以正常使用@RequestBody来验证我的对象.
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(method=RequestMethod.POST)
public CustomerQuickRegisterEntity saveNewCustomer(@Valid @RequestBody CustomerQuickRegisterEntity customerEntity,BindingResult result)
{
if(result.hasErrors())
{
return new CustomerQuickRegisterEntity();
}
return customerQuickRegisterRepository.save(customerEntity);
}
Run Code Online (Sandbox Code Playgroud)
但问题是当我通过这样做将其限制为一个对象时,因为@InitBinder("customerEntity")它没有验证对象.所以我搜索了stackoverflow,发现@InitBinding它只适用于带注释的对象@ModelAttribute.然后我的问题是,@RequestBody当我使用它时工作正常,@InitBinder但是当我使用它时效果不好@InitBinder("customerEntity")......为什么会这样呢?是否有任何其他方法来验证与之关联的对象(不是单独的对象的属性)@RequestBody
这是一个老问题,但我已经设法获得@InitBinder注释以将我的自定义绑定Validator到这样的@Valid @RequestBody参数:
@InitBinder
private void bindMyCustomValidator(WebDataBinder binder) {
if ("entityList".equals(binder.getObjectName())) {
binder.addValidators(new MyCustomValidator());
}
}
Run Code Online (Sandbox Code Playgroud)
如果您尝试通过设置注释的值来过滤绑定参数,那么它将不适用于@RequestBody参数。所以在这里我检查对象名称。我的方法参数实际上是被调用的entities,但 Spring 已经决定调用它entityList。我必须调试它才能发现这一点。
| 归档时间: |
|
| 查看次数: |
8944 次 |
| 最近记录: |