Spring MVC - @ init binder方法未调用

时间:2014-05-13 08:40:07

标签: spring spring-mvc spring-mvc-initbinders

嗨,这是我的控制器

@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());
}

以下是我的验证员

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");
        }
    }
}

问题是我的验证器并非全部被调用。条件bindResult.hasErrors() || bindResult.hasFieldErrors()false。我也试过调试..它不是全部被调用

1 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是将Validator实例化为服务,并注入您的控制器。在您的模型上注释@Validated。

@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";
    }
}

将验证器实例化为服务:

@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");
        }
    }
}