当我有以下带有 JSR-303(验证框架)注释的模型时:
public enum Gender {
MALE, FEMALE
}
public class Profile {
private Gender gender;
@NotNull
private String name;
...
}
以及以下 JSON 数据:
{ "gender":"INVALID_INPUT" }
在我的 REST 控制器中,我想同时处理绑定错误( gender
属性的枚举值无效)和验证错误( name
属性不能为空)。
以下控制器方法不起作用:
@RequestMapping(method = RequestMethod.POST)
public Profile insert(@Validated @RequestBody Profile profile, BindingResult result) {
...
}
这会在绑定或验证发生之前产生 com.fasterxml.jackson.databind.exc.InvalidFormatException
序列化错误。
经过一番摆弄,我想出了这个自定义代码,它可以满足我的需求:
@RequestMapping(method = RequestMethod.POST)
public Profile insert(@RequestBody Map values) throws BindException {
Profile profile = new Profile();
DataBinder binder = new DataBinder(profile);
binder.bind(new MutablePropertyValues(values));
// validator is instance of LocalValidatorFactoryBean class
binder.setValidator(validator);
binder.validate();
// throws BindException if there are binding/validation
// errors, exception is handled using @ControllerAdvice.
binder.close();
// No binding/validation errors, profile is populated
// with request values.
...
}
基本上这段代码的作用是序列化为通用映射而不是模型,然后使用自定义代码绑定到模型并检查错误。
我有以下问题:
- 自定义代码是这里的方式还是在 Spring Boot 中有更标准的方式来执行此操作?
@Validated
注释如何工作?如何制作自己的自定义注释,其工作方式类似于@Validated
来封装我的自定义绑定代码?
原文由 Jaap van Hengstum 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是我在我的一个项目中使用的用于在 Spring Boot 中验证 REST api 的代码,这与您的要求不同,但相同.. 检查这是否有帮助
成功.java
错误.java
你也可以看看这里: Spring REST Validation