简体   繁体   中英

spring initBinder and webbindinginitializer example

I read few books on spring2.5 on these topic, but still cannot grab the concepts when to use @initBinder. can anyone share any reference or explain in what situation i can use this on web application? How propertyEditor relate to it?

Well I can't really put it any better than the books, but if your controller has any public methods annotated with @InitBinder, then these methods will be called by the container just before each request is processed, passing in the WebDataBinder being used by the framework.

The most common reason to do this is when you want to customise the way that Spring tries to bind request parameters on to your model, for example if your model has custom datatypes that Spring can't handle out of the box. You register your PropertyEditors against the WebDataBinder. A trivial example would be if you use the JodaTime library in your model, and you want to bind timestamp strings on to a Joda DateTime object.

With Spring 2.0, you use to have to override the protected initBinder() method from the controller superclass, but Spring 2.5 removes the need to do that, you can just use annotations now.

Another reason beside what skaffman mentioned, would be to set a custom validator on your WebDataBinder. What I will usually do is use JSR-303 bean validation, and then bind a validator that provides additional validation not provided by JSR-303.

Inside your controller:

@InitBinder
protected void initBinder(WebDataBinder webDataBinder) {
    Validator validator = webDataBinder.getValidator();
    webDataBinder.setValidator(new UserFormValidator(validator));
}

What I'm doing is taking in the bean validator, calling that inside my custom validator, and then calling my custom validations. Something like this:

public class UserFormValidator implements Validator {

    private Validator validator;

    public AuthUserFormValidator(Validator validator) {
        this.validator = validator;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return UserForm.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

        // Run the bean validation...

        validator.validate(target, errors);

        // Do your custom validation on userForm here...

        UserForm userForm = (UserForm) target;

        // Validation on userForm...
    }
}

它需要Spring 2.5.1+,请参阅https://jira.springsource.org/browse/SPR-4182

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM