Spring 3 MVC ConstraintValidator验证:未调用isValid方法

时间:2014-05-07 17:23:35

标签: java spring validation spring-mvc web-applications

我是Spring 3 MVC的新手,并试图在this之后实现ConstrainValidation,但验证部分没有用,isValid方法没有被调用。不确定我的配置中是否遗漏了某些内容,以下是我尝试的内容:

Employee.java

public class Employee {

@Phone
private String phone;

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}
}

Phone.java

@Documented
@Constraint(validatedBy = {PhoneValidator.class})
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {

String message() default "{Phone}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}

PhoneValidator.java

public class PhoneValidator  implements ConstraintValidator<Phone, String>{

@Override
public void initialize(Phone phone) {
    // TODO Auto-generated method stub

}

@Override
public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
    if(phoneField == null) {
        return false;
    }
    return phoneField.matches("[0-9()-\\.]*");
}
}

控制器

@RequestMapping(value="done")
public String displaySuccess(@Valid Employee employee,BindingResult result,Model model){
    if(result.hasErrors()){
        System.out.println("Validation Failed!!!");
        return "display";
    }else{
        System.out.println("Validation Succeeded!!!");
        return "done";
    }

}

context.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config />
<context:component-scan
    base-package="com.xxx" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/pages/" />
    <property name="suffix" value=".jsp" />
</bean>
</beans>

有人可以指出我错过了什么吗? Phone验证无效,isValid方法也未被调用。

1 个答案:

答案 0 :(得分:0)

<context:annotation-config />更改为<mvc:annotation-driven />重新解决了我的问题。

参考:

Spring3 MVC: Validation not working