springboot从数据库查询出数据并将上述格式的数据展示在index.html中
时间: 2024-05-10 13:20:55 浏览: 147
1. 在Spring Boot中,可以使用JdbcTemplate或者Spring Data JPA等方式从数据库中查询数据。
2. 假设我们从数据库中查询出以下数据:
```java
List<Map<String, Object>> dataList = jdbcTemplate.queryForList("SELECT name, age, city FROM user");
```
3. 将查询结果转化为指定格式的数据:
```java
List<Map<String, Object>> formattedDataList = new ArrayList<>();
for (Map<String, Object> data : dataList) {
Map<String, Object> formattedData = new LinkedHashMap<>();
formattedData.put("name", data.get("name"));
formattedData.put("age", data.get("age"));
formattedData.put("city", data.get("city"));
formattedDataList.add(formattedData);
}
```
4. 将数据传递给Thymeleaf模板引擎,在index.html中进行展示。
Controller代码:
```java
@GetMapping("/")
public String index(Model model) {
List<Map<String, Object>> dataList = jdbcTemplate.queryForList("SELECT name, age, city FROM user");
List<Map<String, Object>> formattedDataList = new ArrayList<>();
for (Map<String, Object> data : dataList) {
Map<String, Object> formattedData = new LinkedHashMap<>();
formattedData.put("name", data.get("name"));
formattedData.put("age", data.get("age"));
formattedData.put("city", data.get("city"));
formattedDataList.add(formattedData);
}
model.addAttribute("dataList", formattedDataList);
return "index";
}
```
index.html代码:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Thymeleaf Example</title>
</head>
<body>
<h1>Data List</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr th:each="data : ${dataList}">
<td th:text="${data.name}"></td>
<td th:text="${data.age}"></td>
<td th:text="${data.city}"></td>
</tr>
</tbody>
</table>
</body>
</html>
```
阅读全文