可以在运行@Validated之前修改@ModelAttribute

时间:2013-08-05 00:51:49

标签: spring-mvc hibernate-validator

可以在通过@Validated验证之前修改@ModelAttribute。

@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public final ModelAndView save(
        @Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject)

我需要在执行@Validated之前更改myObject的状态

2 个答案:

答案 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触发之前修改模型属性对象:

  1. 删除@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
}

  1. 装饰默认的验证器并预处理装饰的验证器中的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中学到的)