4

我有一个弹簧 mvc 控制器,如下所示

@RequestMapping(value="/new", method=RequestMethod.POST)
public String createBooking(@Valid Booking booking, BindingResult bindingResult, Model model, Principal principal)
{
    if(bindingResult.hasErrors()) {
        return "booking/edit";
    }
    //Store Booking in db...
    ...

问题是我从 POST 获得的 Booking 对象是由 Spring 构造的,但无法填充验证器所需的属性之一,因为该属性不存在于表单中。所以我的问题是我有没有办法在预订被@Valid 标签处理程序处理以添加这个必需的属性之前拦截它?

干杯! NFV

4

2 回答 2

1

@Valid在将触发之前,有两种方法可以修改模型属性对象:

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

  1. 装饰默认验证器并在装饰的验证器内预处理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获得的)

于 2020-06-02T13:53:56.063 回答
0

我不确定我是否理解这个问题,但听起来你想在你的命令被表单提交绑定之前将命令对象中的一个字段设置为一个值。如果是这样,您可以在控制器中添加一个方法,如下所示...

@ModelAttribute
public Booking getBooking() {
    Booking booking = new Booking();
    booking.setMyRequiredProperty("some value");
    return booking;
}

希望有帮助

于 2013-02-06T23:11:26.633 回答