javax.validation.ConstraintViolationException:类验证失败

时间:2018-08-01 18:39:30

标签: spring spring-mvc spring-boot

Stacktrace image

当我尝试向数据库中添加新用户时出现此错误。错误来自我的@PassMatch注解,但我不知道为什么。当密码和确认密码相等时,出现此错误:

  

javax.validation.ConstraintViolationException:验证失败   持续期间的类[mereuta.marian.tennis01.model.Utilisateur]   组的时间[javax.validation.groups.Default,]

     

ConstraintViolationImpl {interpolatedMessage ='le mot de pass est   通过不同的确认方式”,   propertyPath = confirmPassword,rootBeanClass = class   mereuta.marian.tennis01.model.Utilisateur,messageTemplate ='le mot de   通过不同的确认”'

谢谢您的帮助

这是我的@PassMatch批注:

package mereuta.marian.tennis01.annotations;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PassMatchValidator.class)
@Documented
public @interface PassMatch {

    String message() default "{com.moa.podium.util.constraints.matches}";

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

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

    String field();

    String verifyField();
}

这是我的课程PassMatchValidator

package mereuta.marian.tennis01.annotations;

import org.mvel2.MVEL;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PassMatchValidator implements ConstraintValidator<PassMatch, Object> {

    private String field;
    private String verifyField;


    public void initialize(PassMatch constraintAnnotation) {
        this.field = constraintAnnotation.field();
        this.verifyField = constraintAnnotation.verifyField();
    }

    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Object fieldObj = MVEL.getProperty(field, value);
        Object verifyFieldObj = MVEL.getProperty(verifyField, value);

        boolean neitherSet = (fieldObj == null) && (verifyFieldObj == null);

        if (neitherSet) {
            return true;
        }

        boolean matches = (fieldObj != null) && fieldObj.equals(verifyFieldObj);

        if (!matches) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("le mot de pass est 
            different du mot de pass de confirmation")
                    .addNode(verifyField)
                    .addConstraintViolation();
        }

        return matches;
    }
}

这是我的模型:

@PassMatch(field = "password", verifyField = "confirmPassword")
@Entity(name = "utilisateurs")
public class Utilisateur {
    @Column(name = "password")
    private String password;
    @Transient
    private String confirmPassword;
}

0 个答案:

没有答案