news 2026/6/22 19:14:03

SpringBoot整合Thymeleaf

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SpringBoot整合Thymeleaf

一、Thymeleaf 简介

Thymeleaf 是一款现代化的服务器端 Java 模板引擎,主要用于 Web 开发中渲染 HTML 页面,能够无缝集成 Spring Boot 框架。它的核心优势是:

  • 支持 HTML 原生语法,模板文件可直接在浏览器中打开预览(无后端数据时显示默认值);
  • 与 Spring 生态深度整合,是 Spring Boot 推荐的模板引擎;
  • 支持多种表达式、条件判断、循环遍历等动态渲染能力;
  • 无静态标签库,语法简洁易懂。

二、环境搭建(Spring Boot 整合)

1. 依赖引入(pom.xml)

xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> </parent> <dependencies> <!-- Spring Web 核心依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Thymeleaf 核心依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Lombok(可选,简化实体类) --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> </project>

2. 核心配置(application.yml)

yaml

server: port: 8080 spring: thymeleaf: cache: false # 开发环境关闭缓存,修改页面无需重启服务

三、Thymeleaf 基础语法

1. 命名空间声明

所有使用 Thymeleaf 的 HTML 页面,需在<html>标签中声明命名空间,否则 Thymeleaf 表达式无法生效:

html

预览

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2. 变量表达式(${})

作用

从 Spring 容器的 Model 中获取后端传递的数据,是最常用的表达式。

示例
后端传递数据(Controller)

java

运行

package com.qcby.controller; import com.qcby.model.People; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.Arrays; import java.util.Date; @Controller public class IndexController { @GetMapping("/basic") public String basic(Model model) { // 构建实体类对象 People people = new People(); people.setUsername("renliang"); people.setAge(1); people.setSex(1); people.setIsVip(false); people.setBirthday(new Date()); people.setTags(Arrays.asList("PVP","Node","SUC")); // 将数据放入Model,key为"people" model.addAttribute("people", people); return "basic"; // 跳转到templates下的basic.html } }
前端渲染(basic.html)

html

预览

<!-- 直接获取对象属性 --> <h2 th:text="${people.username}"></h2> <p th:text="${people.age}"></p> <!-- 布尔类型判断 --> <p th:if="${people.isVip}">会员</p>

3. 选择变量表达式(*{})

作用

通过th:object指定根对象后,简化属性获取(无需重复写根对象名)。

示例

html

预览

<div th:object="${people}"> <!-- 等价于 ${people.username} --> <h2 th:text="*{username}"></h2> <!-- 等价于 ${people.age} --> <p th:text="*{age}"></p> </div>

4. 文本替换与拼接

(1)字面量拼接(|${}|)

适用于标题、描述等简单拼接场景:

html

预览

<!-- 默认标题为"默认标题",后端传递title则替换为传递的值 --> <title th:text="|${title}|">默认标题</title> <!-- 也可拼接固定文本 --> <title th:text="|用户中心 - ${people.username}|">用户中心</title>
(2)无转义文本(th:utext)

th:text会转义 HTML 标签(如<h1>变为文本),th:utext则保留原生 HTML 效果:

java

运行

// Controller 传递带HTML标签的文本 model.addAttribute("hello", "<h1>zhangsan</h1>");

html

预览

<!-- 显示为纯文本:<h1>zhangsan</h1> --> <div th:text="${hello}"></div> <!-- 显示为H1标题:zhangsan --> <div th:utext="${hello}"></div>

5. 条件判断(th:if /th:unless)

作用

根据条件动态渲染元素,th:if满足条件显示,th:unless满足条件隐藏(与th:if相反)。

示例

html

预览

<!-- 基础条件判断 --> <a th:href="" th:if="${user.getAge() == 2}" >年龄等于2时显示</a> <!-- 多条件组合(and/or/not) --> <p th:if="${user.score >= 60 and user.score < 85}">B</p> <p th:if="${user.score < 60}">C</p> <p th:if="${user.score > 85}">优秀</p> <!-- th:unless 示例(age不等于2时显示) --> <a th:href="" th:unless="${user.getAge() == 2}" >年龄不等于2时显示</a>

6. 分支选择(th:switch /th:case)

作用

类似 Java 的switch-case,实现多分支条件渲染,th:case="*"表示默认分支。

示例

html

预览

<!-- 性别判断:1=男,2=女,其他=默认 --> <div th:switch="${people.sex}"> <p th:case="1">男</p> <p th:case="2">女</p> <p th:case="*">默认</p> </div> <!-- 简化版(无默认分支) --> <span th:switch="${user.gender}"> <p th:case="1">男</p> <p th:case="2">女</p> </span>

7. 循环遍历(th:each)

作用

遍历集合(List / 数组等),渲染列表、表格等重复元素,支持获取循环状态(索引、是否第一个 / 最后一个等)。

基础示例(遍历列表)

java

运行

// Controller 传递用户列表 List<User> uList = new ArrayList<>(); for (int i = 0; i < 10; i++){ User u = new User(); u.setUsername("renliang"+i); u.setPassword("111"+i); uList.add(u); } model.addAttribute("uList", uList);

html

预览

<!-- 遍历uList,a为每个元素,aState为循环状态对象 --> <table> <tr th:each="a,aState:${uList}"> <td th:text="${a.username}"></td> <!-- 用户名 --> <td th:text="${a.password}"></td> <!-- 密码 --> <td th:text="${aState.index}"></td> <!-- 循环索引(从0开始) --> </tr> </table>
循环状态对象常用属性
属性说明
index索引(从 0 开始)
count计数(从 1 开始)
size集合总长度
first是否为第一个元素(boolean)
last是否为最后一个元素(boolean)
even/odd是否为偶数 / 奇数索引(boolean)

8. 动态属性(th:attr / 直接绑定)

作用

动态设置 HTML 标签的属性(如 class、href、value 等),推荐直接使用th:属性名方式(更简洁)。

示例

html

预览

<!-- 动态设置input的value属性 --> <input th:value="${user.getUsername()}"> <!-- 动态设置class(三元表达式) --> <a th:class="${user.getAge() > 2}?'class1':'class2'" >年龄</a> <!-- 动态设置href(拼接URL) --> <a th:href="@{/user/detail(id=${user.id})}">用户详情</a>

四、核心注意事项

  1. 缓存配置:开发环境务必关闭 Thymeleaf 缓存(spring.thymeleaf.cache=false),否则修改页面后需重启服务才能生效;生产环境建议开启缓存提升性能。
  2. 表达式语法
    • 调用对象方法时需注意参数和返回值(如user.getAge()而非user.age(),因 Lombok 生成的 getter 方法是getAge());
    • 布尔类型判断直接使用${对象.布尔属性}(如${people.isVip}),无需加== true
  3. 模板位置:Spring Boot 中 Thymeleaf 模板默认放在src/main/resources/templates目录下,Controller 返回的字符串直接对应模板文件名(无需加.html)。
  4. 命名空间:必须在<html>标签声明xmlns:th="http://www.thymeleaf.org",否则 Thymeleaf 表达式不会被解析。

五、完整示例流程

  1. 编写实体类(如 People、User),使用 Lombok 的@Data简化 getter/setter;
  2. 编写 Controller,通过Model传递数据到模板;
  3. 编写 Thymeleaf 模板,使用上述语法渲染数据;
  4. 启动 Spring Boot 应用,访问对应接口(如/basic/success)查看渲染效果。

例如访问http://localhost:8080/basic,可看到 People 对象的用户名、年龄、标签列表等数据被动态渲染到页面中;访问http://localhost:8080/success,可看到用户列表、条件判断、动态属性等效果。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/22 9:23:02

大厂迷思:为什么顶级工程师会产出难以维护的代码

当你终于通过几轮严苛的技术面试&#xff0c;加入一家享有盛誉的大型科技公司时&#xff0c;往往会对即将接触的代码库抱有极高的期待。你想象着整洁的架构、清晰的文档以及如教科书般完美的逻辑实现。然而现实往往极具冲击力&#xff1a;你所看到的可能是一个由无数补丁堆叠、…

作者头像 李华
网站建设 2026/6/20 16:18:30

多级缓存必要性

Java多级缓存设计&#xff1a;应对微博明星官宣的高并发场景 一、多级缓存原理与必要性 1.1 为什么需要多级缓存&#xff1f; 单级缓存的问题&#xff1a; 性能瓶颈&#xff1a;所有请求都打到同一缓存层&#xff0c;压力集中容错性差&#xff1a;缓存层故障直接影响整体可…

作者头像 李华
网站建设 2026/6/20 19:21:38

attn_scores注意力分计算-记录

querys 是 2*6*2&#xff0c;keys也是2*6*2 attn_scores querys keys.transpose(1,2)attn_scores 最终维度是 266&#xff1b;数值上是两个矩阵的批量矩阵乘法结果&#xff0c;每个样本对应一个 66 的注意力分数矩阵 transpose(1,2) 交换 keys 的第 1 维和第 2 维&#xff1…

作者头像 李华
网站建设 2026/6/15 12:10:29

为什么标准化要用均值0和方差1?

为什么标准化要把均值设为0、方差设为1&#xff1f; 先说均值。均值就是平均数&#xff0c;所有观测值加起来除以个数。 μ是均值&#xff0c;n是数据点总数&#xff0c;xᵢ是每个数据点&#xff0c;所以均值就是数据的重心位置。比如均值是20&#xff0c;那20就是平衡点。这…

作者头像 李华
网站建设 2026/6/21 15:36:05

人群仿真软件:Vadere_(2).Vadere基本操作与界面

Vadere基本操作与界面 启动Vadere 启动过程 Vadere是一款基于Java的人群仿真软件&#xff0c;可以通过以下步骤启动&#xff1a; 安装Java环境&#xff1a;确保您的计算机上安装了Java运行环境&#xff08;JRE&#xff09;或Java开发工具包&#xff08;JDK&#xff09;。您可…

作者头像 李华