Java ThymileAF:按错误代码显示全局错误
如何在模板中按各自的错误代码显示多个全局错误 拒绝绑定结果时,第一个参数是Java ThymileAF:按错误代码显示全局错误,java,spring,spring-boot,spring-mvc,thymeleaf,Java,Spring,Spring Boot,Spring Mvc,Thymeleaf,如何在模板中按各自的错误代码显示多个全局错误 拒绝绑定结果时,第一个参数是错误代码。在模板中显示错误时,如何使用此选项 用例:我在控制器中使用自定义验证规则(例如重复检查),我希望在表单的不同位置显示全局错误 例: 在my Thymeleaf模板中,我可以一次显示所有错误: <form th:object="${myForm}" method="post"> <p th:if="${#fields.hasGlobalErrors()}" th:errors="*{glo
错误代码
。在模板中显示错误时,如何使用此选项
用例:我在控制器中使用自定义验证规则(例如重复检查),我希望在表单的不同位置显示全局错误
例:
在my Thymeleaf模板中,我可以一次显示所有错误:
<form th:object="${myForm}" method="post">
<p th:if="${#fields.hasGlobalErrors()}" th:errors="*{global}"></p>
</form>
但是我怎样才能只打印带有错误代码的错误?我想没有办法。我建议您在对象(myForm)中创建另一个字段,并使用rejectValue指定BindingResult中的错误。然后,您可以验证模板上的错误:
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>
公共字符串myPage(…,BindingResult){
结果。拒绝(“错误代码1”,“发生全局错误”);
result.rejectValue(“newField”,“发生错误2”);
返回“我的观点”
}
希望这有帮助
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>