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

前端之家收集整理的这篇文章主要介绍了java – spring将两个验证注释合二为一前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 Spring Hibernate Spring-MVC.
我想定义一个自定义约束,结合其他两个预定义的验证注释:@NotNull @Size,如下所示:
  1. import javax.validation.constraints.NotNull;
  2. import javax.validation.constraints.Size;
  3.  
  4. @NotNull
  5. @Size(min=4)
  6. public @interface JPasswordConstraint {
  7. } // this is not correct. It's just a suggestion.

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

  1. public class ChangePasswordForm {
  2.  
  3. @NotNull
  4. private String currentPass;
  5.  
  6. @JPasswordConstraint
  7. private String newPass;
  8.  
  9. @JPasswordConstraint
  10. private String newPassConfirm;
  11. }

UserController.java

  1. @RequestMapping(value = "/pass",method = RequestMethod.POST)
  2. public String pass2(Model model,@Valid @modelattribute("changePasswordForm") ChangePasswordForm form,BindingResult result) {
  3. model.addAttribute("changePasswordForm",form);
  4. try {
  5. userService.changePassword(form);
  6. } catch (Exception ex) {
  7. result.rejectValue(null,"error.objec",ex.getMessage());
  8. System.out.println(result);
  9. }
  10. if (!result.hasErrors()) {
  11. model.addAttribute("successMessage","password changed successfully!");
  12. }
  13. return "user/pass";
  14. }

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

解决方法

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

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

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

  1. @NotNull
  2. @Size(min=4)
  3. @Target({ METHOD,FIELD,ANNOTATION_TYPE })
  4. @Retention(RUNTIME)
  5. @Constraint(validatedBy = { })
  6. @Documented
  7. public @interface JPasswordConstraint {
  8. String message() default "Password is invalid";
  9. Class<?>[] groups() default { };
  10. Class<? extends Payload>[] payload() default { };
  11. }

猜你在找的Java相关文章