Spring 类级别验证和 Thymeleaf

标签 spring validation thymeleaf

我正在学习Spring框架和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());    
  }     
}

这是我的 Controller 方法:

@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 中类级别注释返回的默认错误消息吗?

最佳答案

我知道这是旧帖子,但我也遇到了这个问题,这是解决方案(也许它也对其他人有帮助): 将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;

}

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

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

关于Spring 类级别验证和 Thymeleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50785814/

相关文章:

java - Spring:带有带有 @Autowired(required = false) 参数的构造函数的 @Service 类:如何使用这些参数初始化它?

jquery - 使用 jQuery 验证文本字段是否为数字

java - 显示先前在 thymeleaf 中使用 if case 隐藏的标签

java - 作为变量传递时,Thymeleaf 片段无法解析,即 <div th :replace ="${page}">

spring - 如何从 Controller 访问片段中的片段?

java - 控制台上的 DBCL 消息

java - Spring中的@Transaction

java - @Resource 与 @Autowired

validation - 在域驱动设计中应该将输入验证放在哪里?

javascript - 如何在 JavaScript 而不是 HTML 元素中设置 AngularJS 验证