嗨,这是我的控制器
@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
。我也试过调试..它不是全部被调用
答案 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");
}
}
}