我正在尝试使用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验证方法。有什么办法可以简单地做到这一点吗?
您可以使用以下方法在后端设置错误 model.addAttribute("errorMessage", error)
如果存在错误,则将其显示在元素中。例如:
<span th:if="${errorMessage != null}" th:text=${errorMessage}/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句