1

我有一个模型对象,它具有用休眠验证注释注释的实体。例如@NotBlank、@NotNull、@Length。我有一个支持这个模型的表单,它装饰了模型对象的一个​​实例。我已经用@NotNull、@Valid 注释对这个实例进行了注释。我正在控制器类中为此支持表单注册一个验证器,并且当@RequestMapping 方法参数使用@Valid 注释进行注释时,将调用表单验证器。

请注意,模型还使用 @Entity 注释进行了注释,模型支持表单只是模型的一个薄包装。

但是没有检查装饰对象的验证?我知道这一点,因为在请求映射方法定义中,我检查了 BindResult 是否有错误,但没有。我的表单字段都是空的,因此应该检查带有 @NotBlank 注释的装饰模型上的字段的验证。然而,这不会发生。

你能帮我解决这个问题吗?

编辑:示例代码

@Entity
class MyModel {
    @Id
@GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable=false)
    private Long id;

    @NotBlank
    @Column(unique=true, length=30, nullable=false)
    private String number;

    @Column(length=30, nullable=false)
    @Length(min=1, max=30)
private String firstName;
    /* ... getters and setters ... */
}

public class MyModelBackingForm {

   @NotNull
   @Valid
   private MyModel model;
   /* ... delegate getters and setters for all fields in MyModel ...  */
 }

编辑:添加控制器代码

@InitBinder
protected void initBinder(WebDataBinder binder) {
  binder.setValidator(new MyBackingFormValidator());
}

编辑:

public class MyBackingFormValidator implements Validator {

  public MyBackingFormValidator() {
    super();
  }

  @Override
  public boolean supports(Class<?> clazz) {
    return Arrays.asList(MyBackingForm.class, MyModel.class).contains(clazz);
  }

  @Override
  public void validate(Object obj, Errors errors) {
   // custom validation code commented ... as I want to check if JSR 303 validations invoked
  }
}
4

1 回答 1

0

这是我使用休眠验证方式的示例代码。我正在使用绑定结果对获取的对象调用@valid。这样它就知道需要在表单上进行的验证。编辑:如何调用自定义和标准验证器?

使用@InitBinder,我们可以传递自定义验证器实例,我们可以使用 binder.getValidator() 再次将标准验证器的类参数传递给该实例

礼貌:Rohit Banga

@Controller
@RequestMapping("/customer")
public class CustomerController {

//编辑:

@InitBinder 
protected void initBinder(WebDataBinder binder) { 
binder.setValidator(new CustomFormValidator(binder.getValidator())); 
}

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String addCustomer(@Valid Customer customer, BindingResult result) {

        if (result.hasErrors()) {
            return "form";
        } else {
            return "success";
        }

    }

    @RequestMapping(method = RequestMethod.GET)
    public String customerForm(ModelMap model) {

        model.addAttribute("customer", new Customer());
        return "form";

    }

}
于 2012-10-20T07:31:40.473 回答