可以在通过@Validated验证之前修改@ModelAttribute。
即
@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public final ModelAndView save(
@Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject)
我需要在执行@Validated之前更改myObject的状态
答案 0 :(得分:1)
添加ModelAttribute populate方法怎么样?
@ModelAttribute("myObject")
public MyObject modifyBeforeValidate(
@ModelAttribute("myObject") MyObject myObject) {
//modify it here
return myObject;
}
副作用是如果我没弄错的话,将在每个@RequestMapping方法之前调用此方法。
Update1:示例
@ModelAttribute("command")
public ChangeOrderCommand fillinUser(
@ModelAttribute("command") ChangeOrderCommand command,
HttpServletRequest request) {
command.setUser(securityGateway.getUserFrom(request));
return command;
}
@RequestMapping(value = "/foo/bar", method = RequestMethod.POST)
public String change(@ModelAttribute("command") ChangeOrderCommand command,
BindingResult bindingResult, Model model, Locale locale) {
}
答案 1 :(得分:0)
有两种方法可以在@Validated
触发之前修改模型属性对象:
@Validated
并自动连接验证器并手动触发验证器:class MyController {
private final Validator validator;
class MyController(Validator validator) {
this.validator = validator;
}
@PostMapping("/doSomething")
public final ModelAndView save(
@ModelAttribute("myObject") MyObject myObject, BindingResult result) {
// edit MyObject here
validator.validate(myObject, result)
// original method body here
}
myObject
对象。class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(new PreProcessMyObjectValidator(binder.getValidator()));
}
@PostMapping("/doSomething")
public final ModelAndView save(
@Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject, BindingResult result) {
...
}
private static class PreProcessMyObjectValidator implements Validator {
private final Validator validator;
public PreProcessMyObjectValidator(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 MyObject) {
MyObject myObject = (MyObject) target;
// manipulate myObject here
}
validator.validate(target, errors);
}
}
}
(第二个技巧是我从https://github.com/spring-projects/spring-framework/issues/11103中学到的)