springboot的Thymeleaf语法

1. Spring Boot自动配置原理

核心机制

Spring Boot通过@EnableAutoConfiguration注解触发自动配置,结合spring.factories文件中的EnableAutoConfiguration列表加载组件。其核心逻辑如下:

  • 条件化配置 :使用@Conditional系列注解(如@ConditionalOnClass@ConditionalOnMissingBean)判断是否启用配置。

  • 默认配置覆盖 :用户可通过application.properties覆盖默认属性(如数据库连接、端口号)。

  • 扩展性 :通过自定义@Configuration类或扩展WebMvcConfigurer实现个性化配置。

示例

复制代码
# 修改Tomcat端口
server.port=8081
# 关闭Thymeleaf缓存(开发环境建议关闭)
spring.thymeleaf.cache=false

2. 静态资源映射规则

默认资源路径

Spring Boot默认从以下路径加载静态资源(按优先级排序):

  1. classpath:/META-INF/resources/

  2. classpath:/resources/

  3. classpath:/static/

  4. classpath:/public/

  5. 项目根路径/**(如localhost:8080/abc)。

配置类解析

复制代码
@ConfigurationProperties(prefix = "spring.resources")
public class ResourceProperties {
    private List<String> staticLocations; // 静态资源路径
    private int cachePeriod; // 缓存时间(秒)
}

扩展方法

通过实现WebMvcConfigurer自定义资源映射:

复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/custom/**")
                .addResourceLocations("file:D:/uploads/");
    }
}

3. Thymeleaf模板引擎

核心优势

  • 自然语法,无需编译,直接在浏览器中打开HTML调试。

  • 支持HTML5、XML、JavaScript等格式,与Spring Security深度集成。

基本语法

标签 功能 示例
th:text 文本替换(自动转义) <p th:text="${msg}"></p>
th:utext 不转义输出 <div th:utext="${html}"></div>
th:each 循环遍历 <tr th:each="user : ${users}">
th:href 动态生成URL <a th:href="@{/user/{id}(id=${user.id})}">
th:if/th:unless 条件判断 <div th:if="${user.age > 18}">

国际化支持

  • src/main/resources下创建messages_xx.properties文件(如messages_en_US.properties)。

  • 使用#{key}引用国际化文本:

    复制代码
    <button th:text="#{button.submit}"></button>
    <div th:text="#{welcome(${name})}"></div>

4. 配置扩展与最佳实践

静态资源优化

  • WebJars :通过webjars引入前端库(如jQuery),访问路径为/webjars/jquery/3.3.1/jquery.js

  • 欢迎页 :静态资源文件夹下的index.html自动映射到根路径/

Thymeleaf配置

复制代码
# 自定义模板路径和缓存
spring.thymeleaf.prefix=classpath:/custom-templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8

Tymeleaf语法整理

1. 变量表达式与文本输出

HTML示例

复制代码
<!-- 变量表达式 -->
<div th:text="${msg}"></div>
<!-- 不转义输出 -->
<div th:utext="${htmlContent}"></div>

Controller代码

复制代码
@GetMapping("/test")
public String test(Model model) {
    model.addAttribute("msg", "<h1>Hello Thymeleaf</h1>");
    model.addAttribute("htmlContent", "<p>支持HTML标签</p>");
    return "test";
}

说明

  • th:text:自动转义HTML标签,防止XSS攻击。

  • th:utext:直接输出原始HTML内容。

  • 数据通过Model对象传递,键名需与模板中表达式一致。


2. 循环与迭代

HTML示例

复制代码
<!-- 集合遍历 -->
<h3 th:each="user : ${users}" th:text="${user}"></h3>
<!-- 列表索引 -->
<h3 th:each="user, iterStat : ${users}">索引:${iterStat.index}</h3>

Controller代码

复制代码
@GetMapping("/list")
public String list(Model model) {
    model.addAttribute("users", Arrays.asList("Alice", "Bob", "Charlie"));
    return "list";
}

说明

  • th:each支持遍历List、Map、数组。

  • iterStat提供循环状态(索引、是否首尾等)。


3. 表单绑定与对象属性

HTML示例

复制代码
<form th:object="${user}">
    <input th:value="*{name}" placeholder="用户名">
    <input th:value="*{age}" type="number">
</form>

Controller代码

复制代码
@GetMapping("/form")
public String form(Model model) {
    model.addAttribute("user", new User("张三", 25));
    return "form";
}

说明

  • th:object绑定表单对象,*{}访问对象属性。

  • 表单提交时,Thymeleaf自动将输入值映射到Java对象。


4. 链接与URL生成

HTML示例

复制代码
<a th:href="@{/user/{id}(id=${user.id})}">用户详情</a>
<!-- 外部链接 -->
<a th:href="@{https://www.baidu.com}">百度</a>

Controller代码

复制代码
@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id, Model model) {
    model.addAttribute("id", id);
    return "detail";
}

说明

  • @{}生成动态URL,支持路径参数和查询参数。

  • 自动拼接上下文路径(如/app/user/1)。


5. 日期与数值格式化

HTML示例

复制代码
<!-- 日期格式化 -->
<span th:text="${#temporals.format(createTime, 'yyyy-MM-dd')}"></span>
<!-- 数值格式化 -->
<span th:text="${#numbers.formatDecimal(price, 1, 2)}"></span>

Controller代码

复制代码
@GetMapping("/date")
public String dateDemo(Model model) {
    model.addAttribute("createTime", LocalDateTime.now());
    model.addAttribute("price", 99.99);
    return "date-demo";
}

说明

  • #temporals处理日期,#numbers处理数值。

  • 支持自定义格式(如yyyy年MM月dd日)。


6. 国际化(i18n)

HTML示例

复制代码
<!-- 语言切换 -->
<a th:href="@{/i18n?lang=en_US}">English</a>
<a th:href="@{/i18n?lang=zh_CN}">中文</a>

<!-- 国际化文本 -->
<button th:text="#{button.submit}"></button>

资源文件messages_en_US.properties):

复制代码
button.submit=Submit
welcome=Welcome, {0}!

Controller代码

复制代码
@GetMapping("/i18n")
public String i18n(Model model, Locale locale) {
    model.addAttribute("lang", locale.getLanguage());
    return "i18n";
}

说明

  • 通过LocaleResolver解析语言环境。

  • {0}为参数占位符,支持动态替换。


7. 条件判断与逻辑运算

HTML示例

复制代码
<!-- 条件判断 -->
<div th:if="${user.age >= 18}">成年人</div>
<div th:unless="${user.vip}">非VIP用户</div>

<!-- 逻辑运算 -->
<div th:if="${user.score > 90 and user.status == 'active'}">优秀用户</div>

Controller代码

复制代码
@GetMapping("/condition")
public String condition(Model model) {
    model.addAttribute("user", new User("李四", 22, true, 95.5));
    return "condition";
}

说明

  • 支持andornot逻辑运算符。

  • 支持比较运算符(>, <, ==等)。


8. 片段复用与布局

HTML示例

复制代码
<!-- 定义片段 -->
<footer th:fragment="footer">
    <p>版权所有 © 2023</p>
</footer>

<!-- 引用片段 -->
<div th:replace="~{common :: footer}"></div>

Controller代码

复制代码
@GetMapping("/layout")
public String layout() {
    return "layout-demo";
}

说明

  • th:fragment定义可复用代码块。

  • th:replace替换当前内容,th:insert插入内容。


9. 内联表达式与JavaScript

HTML示例

复制代码
<!-- 内联文本 -->
<span>[[${message}]]</span>

<!-- 内联脚本 -->
<script th:inline="javascript">
    var user = [[${user}]];
    console.log(user.name);
</script>

Controller代码

复制代码
@GetMapping("/inline")
public String inline(Model model) {
    model.addAttribute("message", "内联表达式示例");
    model.addAttribute("user", new User("王五", 30));
    return "inline-demo";
}

说明

  • [[...]]用于内联文本,避免转义。

  • th:inline="javascript"传递数据到JS。


总结

Thymeleaf通过声明式语法与Spring Boot无缝集成,核心优势包括:

  1. 自然模板:HTML直接可读,无需预编译。

  2. 动态绑定:支持对象属性、集合遍历、条件判断。

  3. 国际化:通过资源文件实现多语言支持。

  4. 扩展性:自定义格式化器、拦截器等。

最佳实践

  • 使用th:object简化表单绑定。

  • 优先使用th:utext输出富文本内容。

  • 通过#temporals#numbers规范日期/数值格式。

  • 利用片段复用提升模板可维护性。

相关推荐
seven97_top1 小时前
SpringCloud 常见面试题(二)
后端·spring·spring cloud
p***95001 小时前
【SpringBoot】日志文件
java·spring boot·spring
b***66612 小时前
【springboot】健康检查 监控
java·spring boot·后端
明洞日记2 小时前
【设计模式手册010】组合模式 - 树形结构的优雅处理
java·设计模式·组合模式
Slow菜鸟2 小时前
MinIO教程(三)| Spring Boot 集成 MinIO 实战(后端篇)
spring boot·minio
q***47182 小时前
Spring Boot 3.3.4 升级导致 Logback 之前回滚策略配置不兼容问题解决
java·spring boot·logback
databook2 小时前
让你的动画“活”过来:Manim 节奏控制指南 (Rate Functions)
后端·python·动效
n***33352 小时前
SpringBoot返回文件让前端下载的几种方式
前端·spring boot·后端
XUN4J2 小时前
深入浅出谈谈RPC框架
后端