如果我使用@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);
}
但问题是,当我通过这样做将其限制为只有一个对象时@InitBinder("customerEntity")
它没有验证该对象。所以我搜索了 stackoverflow 并发现@InitBinding
仅适用于带有注释的对象@ModelAttribute
。那么我的问题是它工作得很好@RequestBody
当我用它作为@InitBinder
但当我使用它时效果不佳@InitBinder("customerEntity")
……为什么会这样呢?
是否有任何其他方法来验证与关联的对象(不是单独对象的属性)@RequestBody
这是一个老问题,但我已经设法得到了@InitBinder
注释来绑定我的自定义Validator
to a @Valid @RequestBody
参数如下:
@InitBinder
private void bindMyCustomValidator(WebDataBinder binder) {
if ("entityList".equals(binder.getObjectName())) {
binder.addValidators(new MyCustomValidator());
}
}
如果您尝试通过设置注释的值来过滤绑定参数,那么它不适用于@RequestBody
争论。所以这里我改为检查对象名称。我的方法参数实际上被调用entities
,但 Spring 决定将其称为entityList
。我必须调试它才能发现这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)