gpt4 book ai didi

java - 是否可以让我的自定义验证注释在持久化时被忽略?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:50:09 25 4
gpt4 key购买 nike

我使用 Spring 4 和 Hibernate 5

我有带有自定义 validator 的密码字段的用户类。

我需要在表单绑定(bind)时验证它的长度为 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
}

我的 validator

@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();
}
}

Controller 方法

@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;
}

最佳答案

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

可以通过创建接口(interface)来创建群组:

interface FormValidationGroup{}

然后像这样注释 password 字段:

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

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

Hibernate Validator 现在应该忽略 password 字段,除非您指定要验证的组。为了指定一个组来验证 Spring MVC 处理程序方法的参数,请使用 Validated注释而不是 Valid。例如:

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

关于java - 是否可以让我的自定义验证注释在持久化时被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44546172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com