spring - 如何使用 Thymeleaf 模板从 Json 加载数据

标签 spring rest spring-boot thymeleaf

我有一个 rest api 返回一个 Json 值作为服务调用的输出。

例如:- https://localhost:8080/getEmployees/loadAll

这将返回以下 json 值 例如:-

{
"employees":[
  {"firstName":"John", "lastName":"Doe"},
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Peter", "lastName":"Jones"}
]
}

我需要将以下 json 值加载到我的 thymeleaf 表中。 在正常情况下,在 spring 中使用模态在 Controller 中返回值可以将值重新调整为如下列表。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Employee List</title>
</head>
<body>
 <h1>Welcome</h1>
 <br>
 <h3>Employee List</h3>
 <br />
 <table border="1">
  <tr>
   <td>Employee First Name</td>
   <td>Employee Last Name</td>
  </tr>
  <tr th:each="emp : ${empList}">
   <td th:text="${emp.firstName}">First Name</td>
   <td th:text="${emp.name}">Last Name</td>
  </tr>
 </table>
</body>
</html>

有没有一种方法可以使用 thymeleaf 使用上述 json 来完成此操作?

最佳答案

您可以使用以下结构执行类似的操作。

当您调用服务时

https://localhost:8080/getEmployees/loadAll

您需要使用 model.addAttribute 传递员工数据。

例如,假设您有以下方法:

@RequestMapping(value="/getEmployees/loadAll")
String getAllEmployees(Model model) {
    model.addAttribute("empList", <your service here that generates the data>);
    return "pagenamehere";
}

上面的方法,只会在你使用下面的url调用时执行:https://localhost:8080/getEmployees/loadAll 它将添加您的 empList 数据作为属性。然后,返回字符串指示将加载的页面的名称。您将需要使用带有 thymeleaf 代码的自己的页面。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Employee List</title>
</head>
<body>
 <h1>Welcome</h1>
 <br>
 <h3>Employee List</h3>
 <br />
 <table border="1">
  <tr>
   <td>Employee First Name</td>
   <td>Employee Last Name</td>
  </tr>
  <tr th:each="emp : ${empList}">
   <td th:text="${emp.firstName}">First Name</td>
   <td th:text="${emp.lastNname}">Last Name</td>
  </tr>
 </table>
</body>
</html>

现在,thymeleaf 将能够显示给定的数据。

关于spring - 如何使用 Thymeleaf 模板从 Json 加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247470/

相关文章:

java - 如何使用 entityManager 在 JPA 中启动事务

mysql - REST API - 单个与批量 POST/PATCH(SQL 插入/更新)

mysql - Java Spring级联元素集合删除

java - Spring启动执行器endpoints.enabled=false endpoints.health.enabled=true

java - 使用 LoadTimeWeaving 的 Couchbase 的 Spring 缓存 - 奇怪的是不工作

java - Restful PUT 方法的 ModelAttribute 未填充值 ( JSON )

java - Spring:如何在RESTful服务中为@RequestBody添加XSS保护?

java - 如何保护java应用程序中的凭据

Delphi XE2 DataSnap Server - 记录客户端连接用户/属性

spring-boot - 缓存 Cloud Native Buildpacks/Paketo.io pack CLI 在 GitHub Actions 上构建(例如,使用 Spring Boot/Java/Maven buildpacks)?