1

可以在通过@Validated 验证@ModelAttribute 之前对其进行修改。

IE

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

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

4

2 回答 2

1

添加一个 ModelAttribute 填充方法怎么样?

@ModelAttribute("myObject")
public MyObject modifyBeforeValidate(
        @ModelAttribute("myObject") MyObject myObject) {
    //modify it here
    return myObject;
}

副作用是如果我没记错的话,这个方法将在每个 @RequestMapping 方法之前被调用。

更新1:示例

@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) {
}
于 2013-08-05T01:02:45.553 回答
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获得的)

于 2020-06-02T13:49:30.450 回答