【问题标题】:Spring class level validation and ThymeleafSpring 类级别验证和 Thymeleaf
【发布时间】:2018-06-10 16:32:36
【问题描述】:

我正在学习 Spring Framework 和 Thymeleaf。我知道如何使用${#fields.errors("xx")} 之类的东西来显示字段错误。但是,我对如何在 Thymeleaf 中显示对象错误消息感到困惑。

这是我的 UserForm 类:

@PasswordMatches
public class UserForm {
    @NotNull
    @NotEmpty
    private String username;
    @NotNull
    @NotEmpty
    private String password;
    @NotNull
    @NotEmpty
    private String matchingPassword;
    @NotNull
    @NotEmpty
    @ValidEmail
    private String email;

    /* setter and getter methods */

这是我的 PasswordMatches 注释:

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) 
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
@Documented
public @interface PasswordMatches { 
    String message() default "Passwords don't match";
    Class<?>[] groups() default {}; 
    Class<? extends Payload>[] payload() default {};
}

class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {  
    @Override
    public void initialize(PasswordMatches constraintAnnotation) {       
    }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context){   
        UserDto user = (UserDto) obj;
        return user.getPassword().equals(user.getMatchingPassword());    
  }     
}

这是我的控制器方法:

@RequestMapping(value="/registration", method=RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserForm userForm,
          BindingResult result, WebRequest request, Errors errors) {
    if (!result.hasErrors()) {
        return new ModelAndView("registerSuccess");
    }
    else {
        return new ModelAndView("registration", "user", userForm);
    }
}

现在这是我的问题:如果 password 字段和 confirmPass 字段不匹配,如何可以得到 Thymeleaf 中类级别注解返回的默认错误信息吗?

【问题讨论】:

    标签: spring validation thymeleaf


    【解决方案1】:

    我知道这是旧帖子,但我也遇到了这个问题,这是解决方案(也许它也会帮助其他人): 将 PasswordMatchesValidator 修改为:

    class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {  
    @Override
    public void initialize(PasswordMatches constraintAnnotation) {       
    }
    
    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context){   
        UserDto user = (UserDto) obj;
        boolean isValid = user.getPassword().equals(user.getMatchingPassword());
        if(!isValid){
             context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode( "matchingPassword" ).addConstraintViolation();
        }
        return isValid;
    

    }

    它将验证结果绑定到您的“matchingPassword”属性。所以在你的百里香模板中我们是这样的:

    ${#fields.errors("matchingPassword")}
    

    【讨论】:

      【解决方案2】:

      在form 标签内添加这个:

      <p data-th-each="err : ${#fields.allErrors()}" data-th-text="${err}" class="error">
        Invalid input.
      </p>
      

      【讨论】:

      • 感谢您的回复。看来代码是显示所有绑定错误。我想知道是否有一些方法可以指定类级别验证产生的错误。
      • 这个问题有更新吗?我也对同样的问题感到震惊。有没有更好的方法在实体级别而不是从字段级别解决这个问题?
      【解决方案3】:
        <p th:if="${#fields.hasErrors('${yourObject}')}" th:errors="${yourObject}"></p>
      

      【讨论】:

      • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 2012-06-23
      • 2020-09-18
      • 2017-07-14
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      相关资源
      最近更新 更多