我正在学习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/