春季班级验证和Thymeleaf

春季班级验证和Thymeleaf

本文介绍了春季班级验证和Thymeleaf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning Spring Framework and Thymeleaf. I have known how to display field error by using something like ${#fields.errors("xx")}. However, I get stuck about how to display object error message in 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);
    }
}

现在这是我的问题:如果 密码 字段和 confirmPass 字段不匹配,怎么办如何获取Thymeleaf中类级别注释返回的默认错误消息?

Now here is my problem: If the password field and confirmPass field doesn't match, how can I get the default error message returned by the class level annotation in Thymeleaf?

推荐答案

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

I know this is old post but I also encountered this problem and here is the soulution (maybe it will also help someone else):Modify PasswordMatchesValidator to this:

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"属性.因此,在您的百里香模板中,如下所示:

it will bind the validation result to your 'matchingPassword' attribute. So in your thymeleaf template us it like this:

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

这篇关于春季班级验证和Thymeleaf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:12