@Valid
在将触发之前,有两种方法可以修改模型属性对象:
- 移除
@Valid
并自动连接验证器并手动触发验证器:
class MyController {
private final Validator validator;
class MyController(Validator validator) {
this.validator = validator;
}
@PostMapping("/new")
public String createBooking(Booking booking, BindingResult bindingResult, Model model, Principal principal) {
// edit booking here
validator.validate(booking, result)
// original method body here
}
}
- 装饰默认验证器并在装饰的验证器内预处理
booking
对象。
class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(new PreProcessBookingValidator(binder.getValidator()));
}
@PostMapping("/new")
public String createBooking(@Valid Booking booking, BindingResult bindingResult, Model model, Principal principal) {
...
}
private static class PreProcessBookingValidator implements Validator {
private final Validator validator;
public PreProcessBookingValidator(Validator validator) {
this.validator = validator;
}
@Override
public boolean supports(@Nonnull Class<?> clazz) {
return validator.supports(clazz);
}
@Override
public void validate(@Nonnull Object target, @Nonnull Errors errors) {
if (target instanceof Booking) {
Booking booking = (Booking) target;
// manipulate booking here
}
validator.validate(target, errors);
}
}
}
(这第二个技巧是我从https://github.com/spring-projects/spring-framework/issues/11103获得的)