Thymeleaf 中后台数据到前台页面的显示方法

-
2026-01-06

在 Thymeleaf 框架下,你可以通过以下几种方式将后台数据传递到前台页面显示:

1. 基本数据绑定

在 Controller 中:

@GetMapping("/example")
public String example(Model model) {
    model.addAttribute("message", "Hello, Thymeleaf!");
    model.addAttribute("user", new User("张三", 25));
    return "example-page";
}

在前台页面中:

<p th:text="${message}">这里会显示后台传来的消息</p>
<p>姓名: <span th:text=å"${user.name}">默认姓名</span></p>
<p>年龄: <span th:text="${user.age}">默认年龄</span></p>

2. 条件显示

<div th:if="${user.age > 18}">
    成年人内容
</div>
<div th:unless="${user.age > 18}">
    未成年人内容
</div>

3. 循环显示列表数据

Controller 中:

List<String> items = Arrays.asList("苹果", "香蕉", "橙子");
model.addAttribute("items", items);

页面中:

<ul>
    <li th:each="item : ${items}" th:text="${item}">默认项</li>
</ul>

4. 对象列表循环

Controller 中:

List<User> users = Arrays.asList(
    new User("张三", 25),
    new User("李四", 30)
);
model.addAttribute("users", users);

页面中:

<table>
    <tr th:each="user : ${users}">
        <td th:text="${user.name}">姓名</td>
        <td th:text="${user.age}">年龄</td>
    </tr>
</table>

5. 使用内联表达式

<p>欢迎您,[[${user.name}]]!</p>

6. 处理日期格式

Controller 中:

model.addAttribute("now", new Date());

页面中:

<p th:text="${#dates.format(now, 'yyyy-MM-dd HH:mm:ss')}">当前时间</p>

7. 使用 Thymeleaf 片段

定义片段 (fragment.html):

<div th:fragment="userInfo(user)">
    <p th:text="${user.name}">姓名</p>
    <p th:text="${user.age}">年龄</p>
</div>

在页面中使用:

<div th:replace="~{fragment :: userInfo(${currentUser})}"></div>

这些是 Thymeleaf 中最常用的数据展示方式,你可以根据实际需求选择合适的方法。


目录