SpringBoot整合Thymeleaf

Thymeleaf 是 SpringBoot 官方推荐的模板引擎,相比传统 JSP,它语法更简洁、功能更强大,且能直接在浏览器中预览模板效果(无需启动服务),非常适合前后端未完全分离的 SpringBoot 项目。

一、Thymeleaf快速集成

1. 引入依赖

在 SpringBoot 项目的 pom.xml 中引入 Thymeleaf 启动器,SpringBoot 会自动管理其版本(以 SpringBoot 2.0.1 为例,默认集成 Thymeleaf 3.0.9):

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. 自动配置原理

SpringBoot 启动时会通过 ThymeleafAutoConfiguration 类完成自动配置,核心配置由 **ThymeleafProperties**类定义,关键默认属性如下

  • 模板文件默认放在 **resources/templates**目录下

  • 控制器返回的字符串会自动拼接 前缀+返回值+后缀 定位模板(例如返回 "success" 会找 templates/success.html

  • 可在 application.properties 中修改默认配置

java 复制代码
public class ThymeleafProperties {
    public static final String DEFAULT_PREFIX = "classpath:/templates/"; // 模板文件默认存放路径
    public static final String DEFAULT_SUFFIX = ".html"; // 模板文件后缀
    private String mode = "HTML"; // 模板模式
    private boolean cache = true; // 模板缓存(开发建议关闭)
    // 其他编码、校验等配置...
}

3. 快速入门案例

(1)创建模板文件

templates 目录下创建 success.html,引入 Thymeleaf 命名空间(支持语法提示)

html 复制代码
<!DOCTYPE html>
<!-- 在html中引入thymeleaf的命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf入门</title>
</head>
<body>
    <!-- th:text 用于替换文本,会转义HTML标签 -->
    <div th:text="${hello}"></div>
    <!-- th:utext 支持HTML解析,不转义 -->
    <div th:utext="${hello}"></div>
</body>
</html>
(2)编写控制器Controller

创建 Controller 向模板传递数据

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ThymeleafController {

    @RequestMapping("/success")
    public String hello(Model model) {
        // 向模板传递带HTML标签的字符串
        model.addAttribute("hello", "<h1>Hello Thymeleaf!</h1>");
        return "success"; // 对应templates/success.html
    }
}

启动项目访问 http://localhost:8080/success,可看到 th:text 显示原始 HTML 标签,th:utext 解析为 h1 标题

二、Thymeleaf 核心语法

1. 标准表达式语法

Thymeleaf 核心能力通过表达式实现,常用表达式分为 4 类:

表达式类型 语法 说明
变量表达式 ${} 读取 Model/Request/Session 中的数据(Spring EL)
选择表达式 *{} 基于 th:object 选中的对象读取属性,简化代码
国际化表达式 #{} 读取国际化配置文件(.properties)的 key 值
URL 表达式 @{} 生成 URL,自动拼接上下文路径,支持传参

变量表达式 + 选择表达式

html 复制代码
<!-- 变量表达式 -->
<div th:text="${user.username}"></div>

<!-- 选择表达式(需先通过th:object指定对象) -->
<div th:object="${user}">
    <span th:text="*{username}"></span>
    <span th:text="*{age}"></span>
</div>

URL 表达式

html 复制代码
<!-- 基础URL -->
<a th:href="@{/main}">首页</a>
<!-- 带参数的URL -->
<a th:href="@{/user/detail(id=${userId}, name=${userName})}">用户详情</a>
<!-- 表单提交地址 -->
<form th:action="@{/user/save}" method="post">
    <input type="submit" value="提交">
</form>

2. 表达式支持的语法

Thymeleaf 表达式内部支持丰富的运算,满足日常开发需求:

(1)字面量

html 复制代码
<!-- 文本字面量 -->
<div th:text="'Hello ' + ${user.name}"></div>
<!-- 数字字面量 -->
<div th:if="${user.age > 18}">成年</div>
<!-- 布尔字面量 -->
<div th:if="${user.isVip == true}">VIP用户</div>
<!-- 空值判断 -->
<div th:if="${user != null}">用户存在</div>

(2)文本操作

html 复制代码
<!-- 字符串拼接 -->
<div th:text="'姓名:' + ${user.name} + ',年龄:' + ${user.age}"></div>
<!-- 文本替换(更简洁) -->
<div th:text="|姓名:${user.name},年龄:${user.age}|"></div>

(3)算术运算

html 复制代码
<div th:text="${user.score + 10}"></div> <!-- 加法 -->
<div th:text="${user.score / 2}"></div>  <!-- 除法 -->
<div th:text="${user.score % 10}"></div> <!-- 取模 -->

(4)布尔操作

html 复制代码
<div th:if="${user.isVip and user.age > 20}">满足条件</div>
<div th:if="${user.isVip or user.isAdmin}">满足条件</div>
<div th:if="!${user.isVip}">非VIP</div>
<div th:if="not ${user.isVip}">非VIP(等价写法)</div>

(5)比较与等价

html 复制代码
<!-- 比较(>、<、>=、<= 可简写为 gt、lt、ge、le) -->
<div th:if="${user.age gt 18}">成年(gt = >)</div>
<div th:if="${user.age le 60}">未退休(le = <=)</div>
<!-- 等值判断(==、!= 可简写为 eq、ne) -->
<div th:if="${user.gender eq 1}">男</div>
<div th:if="${user.gender ne 1}">女</div>

(6)条件运算符

html 复制代码
<!-- 三元运算符 -->
<div th:text="${user.isVip ? 'VIP用户' : '普通用户'}"></div>
<!-- 默认值(值为空时使用默认值) -->
<div th:text="${user.nickname ?: '默认昵称'}"></div>

3. 常用标签

Thymeleaf 通过 th:* 指令实现动态渲染,核心指令如下:

指令 功能 示例
th:text 文本替换(转义 HTML) <p th:text="${user.desc}">默认描述</p>
th:utext 文本替换(不转义 HTML) <p th:utext="${htmlContent}">默认内容</p>
th:each 循环遍历(支持 List/Map/ 数组) <tr th:each="u, stat : ${userList}">
th:if 条件渲染(满足则显示) <a th:if="${user.id == 1}">编辑</a>
th:unless 条件渲染(不满足则显示) <a th:unless="${user != null}">登录</a>
th:switch/th:case 多路选择 <div th:switch="${user.role}"><p th:case="'admin'">管理员</p></div>
th:value 表单属性赋值 <input th:value="${user.name}">
th:id 替换 ID 属性 <div th:id="'user_' + ${user.id}"></div>
th:class 动态样式类 <a th:class="${user.age>20 ? 'active' : 'default'}">链接</a>
th:selected 下拉框选中 <option th:selected="${item.id == selectedId}">选项</option>
th:src 图片 / 资源路径 <img th:src="@{/img/logo.png}">
th:fragment/th:replace 代码片段复用(布局) <div th:replace="common/header :: header"></div>
html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf语法实战</title>
</head>
<body>
    <!-- 1. 变量与选择表达式 -->
    <div th:object="${user}">
        <h3>用户信息</h3>
        <p>用户名:<span th:text="*{username}"></span></p>
        <p>年龄:<span th:text="*{age}"></span></p>
        <p>等级:<span th:text="*{score >= 85 ? '优秀' : (score >= 60 ? '合格' : '不合格')}"></span></p>
    </div>

    <!-- 2. 条件判断 -->
    <p th:if="${user.gender eq 1}">性别:男</p>
    <p th:if="${user.gender eq 2}">性别:女</p>
    
    <!-- 3. 循环遍历(带状态变量) -->
    <h3>用户列表</h3>
    <table border="1">
        <tr>
            <th>索引</th>
            <th>用户名</th>
            <th>密码</th>
        </tr>
        <tr th:each="u, stat : ${uList}">
            <td th:text="${stat.index}"></td> <!-- 索引(从0开始) -->
            <td th:text="${u.username}"></td>
            <td th:text="${u.password}"></td>
        </tr>
    </table>

    <!-- 4. 动态样式与属性 -->
    <a th:href="@{/user/detail(id=${user.id})}" th:class="${user.age > 2 ? 'class1' : 'class2'}">查看详情</a>
</body>
</html>

对应的controller代码如下

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    @RequestMapping("/user")
    public String user(Model model) {
        // 单个用户
        User user = new User();
        user.setUsername("renliang");
        user.setPassword("123456");
        user.setAge(20);
        user.setScore(78);
        user.setGender(2);
        user.setId(1);

        // 用户列表
        List<User> uList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            User u = new User();
            u.setUsername("renliang" + i);
            u.setPassword("111" + i);
            uList.add(u);
        }

        model.addAttribute("user", user);
        model.addAttribute("uList", uList);
        return "success";
    }

    // 简单的User实体类(lombok简化get/set)
    static class User {
        private Integer id;
        private String username;
        private String password;
        private Integer age;
        private Integer score;
        private Integer gender;

        // 省略getter/setter
        public Integer getId() { return id; }
        public void setId(Integer id) { this.id = id; }
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public Integer getAge() { return age; }
        public void setAge(Integer age) { this.age = age; }
        public Integer getScore() { return score; }
        public void setScore(Integer score) { this.score = score; }
        public Integer getGender() { return gender; }
        public void setGender(Integer gender) { this.gender = gender; }
    }
}

三、Thymeleaf 优势

Thymeleaf 作为 SpringBoot 官方推荐的模板引擎,核心优势在于:

  1. 语法简洁直观,与 HTML 原生标签融合,学习成本低;

  2. 支持前端预览(直接打开 HTML 文件),开发效率高;

  3. 内置丰富的表达式和指令,满足动态渲染、循环、条件判断等所有场景;

  4. SpringBoot 自动配置加持,集成零配置,开箱即用。

相关推荐
程序员乐只2 小时前
基于Python+Django+SSM热门旅游景点推荐系统(源码+LW+调试文档+讲解等)/热门旅游地推荐平台/旅游景点推荐软件/热门景点推荐系统/旅游推荐系统/旅游景点热门推荐
spring boot·spring·tomcat·hibernate·java-zookeeper·guava·java-consul
计算机毕业设计开发2 小时前
django高校公寓管理系统--附源码64226
java·c++·spring boot·python·spring cloud·django·php
季明洵2 小时前
Java中哈希
java·算法·哈希
组合缺一2 小时前
Claude Code Agent Skills vs. Solon AI Skills:从工具增强到框架规范的深度对齐
java·人工智能·python·开源·solon·skills
学海无涯书山有路2 小时前
Android ViewBinding 新手详解(Java 版)—— 结合 ViewModel+LiveData 实战
android·java·开发语言
jaysee-sjc2 小时前
【练习十】Java 面向对象实战:智能家居控制系统
java·开发语言·算法·智能家居
观音山保我别报错2 小时前
Spring Boot 项目学习内容详解(一)
spring boot·后端·学习
哪里不会点哪里.2 小时前
Spring Boot 启动原理深度解析
java·spring boot·后端
零基础的修炼2 小时前
算法---常见位运算总结
java·开发语言·前端