ConstraintValidatorContext用于定义自定义错误消息

时间:2016-05-09 10:37:48

标签: java spring validation constraints

我想使用注释创建自定义电子邮件验证程序。 This solution was useful while creating the validator. 这是注释:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,           ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {CommonsEmailValidator.class})
@Documented
@ReportAsSingleViolation
public @interface ExEmailValidator {

String message() default "        {org.hibernate.validator.constraints.Email.message}";

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

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

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,          ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface List {
ExEmailValidator[] value();
}
}

这里是CommonsEmailValidator类:

public class CommonsEmailValidator implements         ConstraintValidator<ExEmailValidator, String> {
private static final boolean ALLOW_LOCAL = false;
private EmailValidator realValidator =        EmailValidator.getInstance(ALLOW_LOCAL);

@Override
public void initialize(ExEmailValidator email) {
// TODO Auto-generated method stub  
}
@Override
public boolean isValid(String email, ConstraintValidatorContext         constraintValidatorContext) {
 if( email == null ) return true;
 return realValidator.isValid(email);
 }

 }

我运行该项目,但是,当我点击注册表单上的提交时,虽然电子邮件格式无效,但我有以下例外:

请求处理失败;嵌套异常是javax.validation.ConstraintViolationException:在组的持续时间内[...]类的验证失败[javax.validation.groups.Default,]

error 500

异常是如此,但是我希望看到一条错误消息,而不是显示500错误。 所以,我认为我必须使用ConstraintValidatorContext来定义自定义错误消息。但是,我不知道该怎么做。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您应该使用About.cshtml并使用@ControllerAdvice处理验证例外。