gpt4 book ai didi

应用@valid之前的spring mvc进程对象

转载 作者:行者123 更新时间:2023-12-01 23:23:27 27 4
gpt4 key购买 nike

我有一个如下所示的 spring mvc Controller

@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 标记处理程序处理 Booking 之前拦截 Booking 以添加此必需属性?

干杯!网络功能虚拟化

最佳答案

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

  1. 删除 @Valid 并 Autowiring 验证器并手动触发验证器:
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 中学到的)

    关于应用@valid之前的spring mvc进程对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14732598/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com