java – spring将两个验证注释合二为一

前端之家收集整理的这篇文章主要介绍了java – spring将两个验证注释合二为一前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 Spring Hibernate Spring-MVC.
我想定义一个自定义约束,结合其他两个预定义的验证注释:@NotNull @Size,如下所示:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@NotNull
@Size(min=4)
public @interface JPasswordConstraint {
} // this is not correct. It's just a suggestion.

我想在我的表单模型中使用此注释.

public class ChangePasswordForm {

  @NotNull
  private String currentPass;

  @JPasswordConstraint
  private String newPass;

  @JPasswordConstraint
  private String newPassConfirm;
}

UserController.java

@RequestMapping(value = "/pass",method = RequestMethod.POST)
public String pass2(Model model,@Valid @modelattribute("changePasswordForm") ChangePasswordForm form,BindingResult result) {
    model.addAttribute("changePasswordForm",form);
    try {
        userService.changePassword(form);
    } catch (Exception ex) {
        result.rejectValue(null,"error.objec",ex.getMessage());
        System.out.println(result);
    }
    if (!result.hasErrors()) {
        model.addAttribute("successMessage","password changed successfully!");
    }
    return "user/pass";
}

但它不起作用.它接受少于4个字符的密码.
我怎么解决这个问题?

解决方法

这有点晚了,但结合了验证注释的技术

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=5.4#section-constraint-composition

在撰写本文时,可能没有它,但解决方案正在跟进

@NotNull
@Size(min=4)
@Target({ METHOD,FIELD,ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
@Documented
public @interface JPasswordConstraint {
    String message() default "Password is invalid";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
 }
原文链接:https://www.f2er.com/java/120851.html

猜你在找的Java相关文章