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



我试图用Spring做CRUD操作。我在前端使用HTML和百里香。我使用我编写的自定义类返回我所执行的某些操作的结果和错误消息(如果有的话)。到目前为止我还没有遇到任何问题。但是,如果在这些操作过程中发生错误,并且我通过编写的类返回该错误,我不知道如何使用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;
}
}

My error class;

@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";
}

My HTML code;

<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验证方法。有没有办法在中简单的中做到这一点路吗?

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

设置后端错误,如果存在error,则在元素中显示。例如:

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

相关内容

  • 没有找到相关文章

最新更新