Thymeleaf怎么展示数据库数据
时间: 2024-08-12 12:07:16 浏览: 34
Thymeleaf是一个强大的模板引擎,常用于Spring MVC项目中与Java后端交互,用来动态渲染HTML页面。要使用Thymeleaf展示数据库数据,你需要遵循以下步骤:
1. **配置Spring Data JPA**:确保你的Spring Boot应用配置了JPA和数据源,以便从数据库获取数据。
2. **创建Repository接口**:定义一个Repository接口,继承自Spring Data JPA的接口,例如`JpaRepository`或自定义的接口,用于执行CRUD操作。
```java
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAll();
}
```
3. **服务层处理数据**:在Service或Controller里注入Repository,执行查询并返回数据。
```java
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getUsersFromDatabase() {
return userRepository.findAll();
}
}
```
4. **Thymeleaf视图层**:在HTML模板中使用Thymeleaf表达式(Thymeleaf的语法为`#{}`)来插入数据。
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<table>
<tr th:each="user : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
</tr>
</table>
</body>
</html>
```
在上面的代码中,`${users}`是一个Thymeleaf变量,它会被传入的用户列表数据替换。