如何在模板中按各自的错误代码显示多个全局错误?
当拒绝绑定结果时,第一个参数是error code
。在模板中显示错误时如何使用它?
用例:我在控制器中使用自定义验证规则(例如重复检查),并且我想在表单中的不同位置显示全局错误。
Ex:
public String myPage(..., BindingResult result) {
result.reject("errorCode1", "Error 1 happened");
result.reject("errorCode2", "Error 2 happened");
return "my-view"
}
在我的 Thymeleaf 模板中,我可以一次显示所有错误:
<form th:object="${myForm}" method="post">
<p th:if="${#fields.hasGlobalErrors()}" th:errors="*{global}"></p>
</form>
但我怎样才能打印only带有错误代码的错误errorCode1
?
我认为没有办法做到这一点。我建议您在对象 (myForm) 中创建另一个字段,并在 BindingResult 中使用rejectValue 分配错误。然后您可以验证模板上的错误:
public String myPage(..., BindingResult result) {
result.reject("errorCode1", "Global Error Happened");
result.rejectValue("newField", "Error 2 happened");
return "my-view"
}
<form th:object="${myForm}" method="post">
<p th:if="${#fields.hasGlobalErrors()}" th:errors="*{global}"></p>
<p th:if="${#fields.hasErrors('newField')}" th:errors="*{newField}"></p>
</form>
希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)