是否可以使我的自定义验证注释在持久性上被忽略?

时间:2017-06-14 13:25:41

标签: java spring hibernate validation persistence

我使用Spring 4和Hibernate 5

我的User类带有自定义验证器的密码字段。

我需要在表单绑定时验证它,长度为8个字符,包括小写和大写字母以及数字。

当用户输入密码时,它有效,但在编码时无效。

那么有没有办法让我的自定义验证注释在持久化时被忽略?

我知道我可以为未加密的密码创建不同的字段,或者创建数据传输对象,验证它然后将其传递给用户。 但我对注释参数化的可能性很感兴趣。

@Entity
@Table(name = "user")
public class User { 
//other fields

@NotNull
@NotEmpty
@ValidPassword
@Column(name = "password", nullable = false, length = 60)
private String password;
//getters and setters 
}

我的验证员

@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
@Documented
public @interface ValidPassword {
String message() default "Password is too short! Must be 8 digits and    include lowercase, uppercase letters and numbers.";

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

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

public class PasswordValidator implements ConstraintValidator<ValidPassword, String> {

private Pattern pattern;
private Matcher matcher;
private static final String PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,})";

@Override
public void initialize(ValidPassword constraintAnnotation) {
}

@Override
public boolean isValid(String password, ConstraintValidatorContext context) {
    return (validate(password));
}

private boolean validate(String password) {
    pattern = Pattern.compile(PATTERN);
    matcher = pattern.matcher(password);
    return matcher.matches();
}
}

控制器方法

@RequestMapping(value = "/registeruser", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("user") @Valid User user, BindingResult result, Model model) {
    if (result.hasErrors()) {
        model.addAttribute("errorSummary", result.getFieldErrors().stream()
                .map(e -> e.getField() + " error - " + e.getDefaultMessage() + " ").collect(Collectors.toList()));
        model.addAttribute("user", user);

    } else {
        User registered = null;
        registered = createUserAccount(user, result);

        if (registered == null) {
            model.addAttribute("errorSummary", "User with this email already registered!");
            model.addAttribute("user", user);
            return "registration";
        }
        model.addAttribute("flashMessage", "User registered successfully!");
    }

    return "registration";
}

UserService实现方法(我对密码进行编码)

@Transactional
@Override
public User registerNewUserAccount(User user) throws EmailExistsException {

    if (emailExist(user.getEmail())) {
        throw new EmailExistsException("There is an account with that email address:" + user.getEmail());
    }

    if (user.getPassword() == null) {
        user.setPassword(new BigInteger(130, new SecureRandom()).toString(32));
        System.out.println("+++++++++++++++" + user.getPassword());
    }
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    user.setUserRole(new HashSet<UserRole>(1));
    user.getUserRole().add(new UserRole(user, Constants.RoleType.USER.name()));
    save(user);
    return user;
}

1 个答案:

答案 0 :(得分:1)

默认情况下,所有约束都会进行验证。或者您可以指定Grouping Constraints

您可以通过创建界面来创建组:

interface FormValidationGroup{}

并注释password字段,如下所示:

@ValidPassword(groups = FormValidationGroup.class)
private String password;

Custom Constraints annotations的文档,其中提到了groups参数。

除非您指定要进行验证的组,否则Hibernate Validator现在应忽略password字段。要指定用于验证Spring MVC处理程序方法的参数的组,请使用Validated注释而不是Valid。 E.g:

String registerUser(@ModelAttribute @Validated(FormValidationGroup.class) User user,
        BindingResult result, Model model) {
    if (result.hasErrors()) {