【问题标题】:Thymeleaf: display global errors by error codeThymeleaf:通过错误代码显示全局错误
【发布时间】:2020-02-12 02:54:37
【问题描述】:

如何在我的模板中按各自的错误代码显示多个全局错误?

拒绝绑定结果时,第一个参数是error code。在我的模板中显示错误时如何使用它?

用例:我在控制器中使用自定义验证规则(例如重复检查),我想在表单的不同位置显示全局错误。

例如:

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>

但是我怎样才能只打印错误代码为errorCode1的错误?

【问题讨论】:

    标签: java spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    我认为没有办法做到这一点。我建议您在对象 (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>
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 2018-12-07
      • 1970-01-01
      • 2021-04-16
      • 2016-04-11
      • 1970-01-01
      相关资源
      最近更新 更多