如何使用 Thymeleaf 显示自定义错误消息?

时间:2021-01-23 17:35:03

标签: spring thymeleaf

我正在尝试使用 Spring 进行 CRUD 操作。我在前端使用 HTML 和 Thymeleaf。我使用我编写的自定义类返回我所做的某些操作的结果和错误消息(如果有)。到目前为止我没有任何问题。但是,如果在这些操作过程中发生错误并且我通过我编写的类返回此错误,我不知道如何使用 Thymeleaf 将其显示在 HTML 上。

我正在返回一个此类类型的对象;

@Getter
@Setter
public class WarehouseAPIResponseHolder<T> {

    private T responseData;
    private HttpStatus httpStatus;
    private WarehouseAPIResponseError error;

    public WarehouseAPIResponseHolder(HttpStatus httpStatus) {
        this.httpStatus = httpStatus;
    }

    public WarehouseAPIResponseHolder(T responseData, HttpStatus httpStatus) {
        this.responseData = responseData;
        this.httpStatus = httpStatus;
    }

    public WarehouseAPIResponseHolder(HttpStatus httpStatus,
                                      WarehouseAPIResponseError error) {
        this.httpStatus = httpStatus;
        this.error = error;
    }

}

我的错误类;

@Getter
@Builder
public class WarehouseAPIResponseError {

    private String code;
    private String message;

}

错误示例;

if (CollectionUtils.isEmpty(warehouseEntities)) {
            return new WarehouseAPIResponseHolder<>(HttpStatus.NOT_FOUND, WarehouseAPIResponseError
                    .builder()
                    .code("DATA_NOT_FOUND")
                    .message("No records found in the database.")
                    .build());
        }

我的控制器类中的方法;

@GetMapping
    public String getAllWarehouses(Model model) {
        model.addAttribute("listOfWarehouses",warehouseCRUDService.list().getResponseData());
        return "warehouses";
    }

我的 HTML 代码;

<div class="container my-2">
    <h1 align="center">Warehouse List</h1>
    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>Code</th>
            <th>Name</th>
            <th>Status</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="warehouse : ${listOfWarehouses}">
            <td th:text="${warehouse.id}"></td>
            <td th:text="${warehouse.code}"></td>
            <td th:text="${warehouse.name}"></td>
            <td th:text="${warehouse.status}"></td>
        </tr>
        </tbody>
    </table>
</div>

我已成功上架,但如果出现错误消息,我不知道如何显示。我没有使用 Spring 验证方法。有什么办法可以简单做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用 model.addAttribute("errorMessage", error)

在后端设置错误

如果存在错误,则将其显示在元素中。例如:

<span th:if="${errorMessage != null}" th:text=${errorMessage}/>
相关问题