springspring-mvcspring-mvc-initbinders

Spring MVC - @ init binder method not called


Hi this is my controller

@RequestMapping(value="/home", method = RequestMethod.POST)
public String homeSubmit(@Valid LoginForm loginForm , BindingResult bindResult){

    if(bindResult.hasErrors() ||  bindResult.hasFieldErrors() ){
        return "home";
    }else{
        return "Success";
    }
}

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

following is my validator

public class LoginFormValidator implements Validator {

    public boolean supports(Class<?> classz) {
        return LoginForm.class.equals(classz); 
    }

    public void validate(Object target, Errors arg1) {
        System.out.println("inside validate method validator");
        LoginForm loginForm = (LoginForm) target;
        if(! loginForm.getUserName().equalsIgnoreCase("xxx")  ){
            arg1.rejectValue("userName","Invalid Data");
        }
        if(! loginForm.getPassword().equalsIgnoreCase("yyy")){
            arg1.rejectValue("password","Invalid Data");
        }
    }
}

Problem is my validator is not all getting called.evertime the conditions bindResult.hasErrors() || bindResult.hasFieldErrors() is false.I also tried debugging..It is not all getting called


Solution

  • One way to do this is to instantiate Validator as service, and inject into to your controller. Annotate @Validated on your model.

    @Autowired
    @Qualifier("loginFormValidator")
    private Validator validator;
    
    @RequestMapping(value="/home", method = RequestMethod.POST)
    public String homeSubmit(@Validated LoginForm loginForm , BindingResult bindResult){
    
        if(bindResult.hasErrors() ||  bindResult.hasFieldErrors() ){
            return "home";
        }else{
            return "Success";
        }
    }
    

    Instantiate your validator as service:

    @Service("loginFormValidator")
    public class LoginFormValidator implements Validator {
    
        public boolean supports(Class<?> classz) {
            return LoginForm.class.equals(classz); 
        }
    
        public void validate(Object target, Errors arg1) {
            System.out.println("inside validate method validator");
            LoginForm loginForm = (LoginForm) target;
            if(! loginForm.getUserName().equalsIgnoreCase("xxx")  ){
                arg1.rejectValue("userName","Invalid Data");
            }
            if(! loginForm.getPassword().equalsIgnoreCase("yyy")){
                arg1.rejectValue("password","Invalid Data");
            }
        }
    }