开发者

Spring Validation - Programmatically bind to a Validator

I am trying to use Spring validation to validate my model populated by Jackson converter. So I have a java class,

class MyClass(){
    private String myString;
}

This class is populated by Jackson and I have the instance 开发者_JAVA技巧in my Java code. Have also defined a validator class like,

class MyValidator implements Validator {
    public boolean supports(Class<?> clazz) {
        return MyClass.class.equals(clazz);
    }   
    public void validate(Object object, Errors errors) {
           //Validation logic here
    }
}

Now what I wanted to do was to send the object to the validator and get the errors object, examine and proceed further. But, for calling

validate(Object object,Errors errors) 

I need an errors instance which I dont have. I cant use BindingResult or Errors. Please advise on how to proceed further.


You can do this manually in code with a DataBinder:

MyClass toValidate = new MyClass();
DataBinder binder = new DataBinder(toValidate);
binder.setValidator(new MyValidator());
binder.validate();
if (binder.getBindingResult().hasErrors()) {
    // oh noes!
}

Although if you've got a @ModelAttribute defined in a @Controller in spring-mvc, something like this should work (placed inside the relevant @Controller):

@ModelAttribute("myclass")
public MyClass myClass() {
    return new MyClass();
}

@InitBinder("myclass")
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(new MyValidator());
}

@RequestMapping(value = "/do/something", method = POST)
public ModelAndView validatedRequest(@Valid @ModelAttribute("myclass") MyClass profile,
                                     BindingResult result) {
    if (result.hasErrors()) {
        // oh noes!
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜