Thymeleaf中显示@AssertTrue方法验证错误时出现属性不可读问题
解决@AssertTrue验证错误在Thymeleaf中无法显示的问题
问题原因
你遇到的NotReadablePropertyException是因为Thymeleaf的*{passwordMatch}表达式会通过Spring的BeanWrapper尝试读取passwordMatch属性,但你的RegistrationForm类中既没有这个属性,也没有可访问的getter方法(原isPasswordMatch()是private修饰),导致无法识别该属性。
同时,Spring Validation会将isXXX()格式的验证方法的错误标记为XXX字段错误,但Thymeleaf需要对应的属性或public getter才能解析这个字段。
解决方案
方案1:修改验证方法的可见性并处理空指针
将isPasswordMatch()改为public,让Spring BeanWrapper可以识别它作为passwordMatch属性的getter,同时避免空指针异常:
public class RegistrationForm { private String password; private String confirm; @AssertTrue(message = "Passwords don't match") public boolean isPasswordMatch() { // 先判断password不为null,避免空指针 return password != null && password.equals(confirm); } // 其他getter/setter }
之后就可以正常使用Thymeleaf代码显示错误:
<span th:if="${#fields.hasErrors('passwordMatch')}" th:errors="*{passwordMatch}"></span>
方案2:将错误绑定到已有字段(推荐)
如果希望密码不匹配的错误显示在password或confirm字段下方,可以使用@ScriptAssert注解替代@AssertTrue,直接指定错误关联的字段:
@ScriptAssert( lang = "javascript", script = "_this.password == _this.confirm", message = "Passwords don't match", reportOn = "password" // 将错误绑定到password字段 ) public class RegistrationForm { private String password; private String confirm; // getter/setter }
然后用你原本的字段错误显示方式即可:
<span th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></span>
方案3:显示全局错误
如果不想修改Java代码,可以直接在Thymeleaf中遍历全局错误(方法级验证的默认错误属于全局错误):
<div th:if="${#fields.hasGlobalErrors()}"> <span th:each="error : ${#fields.globalErrors()}" th:text="${error.message}"></span> </div>
内容的提问来源于stack exchange,提问作者SquidXTV
相关产品推荐
相关产品推荐

