当前位置: 首页 > news >正文

thymeleaf模板引擎

Thymeleaf 是 SpringBoot 推荐的服务端模板引擎,能在 HTML 中直接嵌入表达式、循环、条件判断等逻辑,同时保持页面 “纯 HTML 可预览” 的特性(无需启动服务也能看静态效果)。

引入thymeleaf

在 SpringBoot 项目中引入 Thymeleaf 只需两步:

步骤 1:添加依赖(Maven 示例)

pom.xml 中加入 Thymeleaf 启动器依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

步骤 2:了解默认配置(由 ThymeleafProperties 管理)

SpringBoot 对 Thymeleaf 做了默认配置,核心规则:

  • 模板文件默认存放在 classpath:/templates/ 目录下;
  • 模板文件后缀默认是 .html
  • 配置前缀可通过 spring.thymeleaf.prefix 修改,后缀可通过 spring.thymeleaf.suffix 修改(如自定义模板目录为 classpath:/views/,可在 application.properties 中配置:spring.thymeleaf.prefix=classpath:/views/)。
thymeleaf语法

Thymeleaf 语法通过 “属性前缀 th: 在 HTML 标签中嵌入逻辑,以下是核心语法及示例:

  1. 变量表达式 ${...}:获取模型数据

用于从SpringMVC传递的 Model 中获取数据

**示例:**Controller 传递用户信息到页面。

// Controller 代码
@GetMapping("/user")
public String getUser(Model model) {User user = new User(1, "张三", 25);model.addAttribute("user", user);return "user"; // 对应 templates/user.html
}// 实体类 User
public class User {private Integer id;private String name;private Integer age;// 省略 getter/setter和构建器
}
<!-- templates/user.html -->
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>用户信息</title>
</head>
<body><!-- 直接获取 user 对象的属性 --><p>ID:<span th:text="${user.id}"></span></p><p>姓名:<span th:text="${user.name}"></span></p><p>年龄:<span th:text="${user.age}"></span></p>
</body>
</html>
  1. 选择表达式 *{...}:基于对象选择属性

    需先通过 th:object 指定 “对象上下文”,再在内部用 *{属性名} 读取,适合对象属性较多的场景。

    **示例:**优化用户信息展示,用选择表达式简化代码。

    <!-- templates/user.html 优化后 -->
    <!DOCTYPE html>
    <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
    <head><meta charset="UTF-8"><title>用户信息</title>
    </head>
    <body><!-- 先指定对象上下文为 user --><div th:object="${user}"><p>ID:<span th:text="*{id}"></span></p><p>姓名:<span th:text="*{name}"></span></p><p>年龄:<span th:text="*{age}"></span></p></div>
    </body>
    </html>
    
  2. 链接表达式 @{...}:生成 URL

    用于生成绝对 / 相对 URL,自动处理上下文路径(避免硬编码)。

    **示例:**页面中添加跳转链接、资源引用。

    <!-- 生成页面跳转链接 -->
    <a th:href="@{/index}">返回首页</a><!-- 引入静态资源(如 CSS、JS) -->
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <script th:src="@{/js/main.js}"></script><!-- 带参数的 URL -->
    <a th:href="@{/user/detail(id=${user.id})}">查看详情</a>
    
  3. 条件判断 th:if/th:unless/th:switch:控制元素显示
    • th:if:条件为 true 时显示元素;
    • th:unless:条件为 false 时显示元素(与 th:if 相反);
    • th:switch+th:case:多分支判断。

    **示例:**根据用户年龄显示不同提示。

    <div th:object="${user}"><!-- th:if 示例:年龄≥18 显示“成年” --><p th:if="*{age} >= 18">您已成年</p><!-- th:unless 示例:年龄<18 显示“未成年” --><p th:unless="*{age} >= 18">您未成年</p><!-- th:switch 示例:根据年龄区间提示 --><div th:switch="*{age}"><p th:case="18">刚成年</p><p th:case="25">青年</p><p th:case="*">其他年龄</p></div>
    </div>
    
  4. 循环遍历 th:each:遍历集合 / 数组

    用于遍历 List、Map、数组等,可获取元素、索引、状态(是否第一个 / 最后一个等)。

    **示例:**展示用户列表。

    // Controller 传递用户列表
    @GetMapping("/user/list")
    public String getUserList(Model model) {List<User> userList = Arrays.asList(new User(1, "张三", 25),new User(2, "李四", 30),new User(3, "王五", 22));model.addAttribute("userList", userList);return "user-list";
    }
    
    <!-- templates/user-list.html -->
    <!DOCTYPE html>
    <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
    <head><meta charset="UTF-8"><title>用户列表</title>
    </head>
    <body><table border="1"><tr><th>序号</th><th>ID</th><th>姓名</th><th>年龄</th><th>状态</th></tr><!-- 遍历 userList,status 是状态变量(包含索引、是否第一个等) --><tr th:each="user, status : ${userList}"><td th:text="${status.index + 1}"></td> <!-- 索引从 0 开始,+1 后显示序号 --><td th:text="${user.id}"></td><td th:text="${user.name}"></td><td th:text="${user.age}"></td><td th:text="${status.first ? '第一个' : (status.last ? '最后一个' : '中间项')}"></td></tr></table>
    </body>
    </html>
    
  5. 内置对象:简化常用操作

    Thymeleaf 提供了大量内置对象(如 #strings#numbers#dates 等),用于字符串、数字、日期的格式化。

    **示例:**格式化日期、字符串拼接。

    <div th:object="${user}"><!-- 假设 user 有 birthday 字段(Date 类型) --><p>生日:<span th:text="${#dates.format(*{birthday}, 'yyyy-MM-dd')}"></span></p><!-- 字符串拼接 --><p>信息:<span th:text="'姓名:' + *{name} + ',年龄:' + *{age}"></span></p><!-- 字符串工具:判断非空、转大写 --><p th:if="${#strings.isEmpty(*{name})}">姓名为空</p><p>姓名大写:<span th:text="${#strings.toUpperCase(*{name})}"></span></p>
    </div>
    
  6. 表单与数据绑定(th:field

    在前后端交互中,表单提交是高频场景,Thymeleaf 的 th:field 可简化表单字段与模型的绑定。

    **示例:**用户注册表单,自动绑定实体类字段。

    // 实体类 UserForm
    public class UserForm {private String username;private String password;private Integer age;// 省略 getter/setter
    }// Controller 代码
    @GetMapping("/register")
    public String register(Model model) {model.addAttribute("userForm", new UserForm());return "register";
    }@PostMapping("/register")
    public String doRegister(@ModelAttribute UserForm userForm) {// 处理表单提交逻辑return "success";
    }
    
    <!-- templates/register.html -->
    <!DOCTYPE html>
    <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
    <head><meta charset="UTF-8"><title>用户注册</title>
    </head>
    <body><form th:action="@{/register}" th:object="${userForm}" method="post"><!-- th:field 自动绑定 username 字段,包含 name、id、value --><input type="text" th:field="*{username}" placeholder="请输入用户名"><br><input type="password" th:field="*{password}" placeholder="请输入密码"><br><input type="number" th:field="*{age}" placeholder="请输入年龄"><br><button type="submit">提交</button></form>
    </body>
    </html>
    
  7. 国际化(多语言支持)

    Thymeleaf 可结合 SpringBoot 实现页面多语言切换,核心是配置 messages_xx.properties 资源文件。

    • 步骤 1:配置国际化资源文件

      resources 目录下创建:

      • messages.properties(默认语言):

        user.name=姓名
        user.age=年龄
        button.submit=提交
        
      • messages_en.properties(英文):

        user.name=Name
        user.age=Age
        button.submit=Submit
        
    • 步骤 2:页面中使用国际化文本

      <!DOCTYPE html>
      <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
      <head><meta charset="UTF-8"><title>国际化示例</title>
      </head>
      <body><!-- 直接使用国际化 key --><p th:text="#{user.name}">姓名</p><p th:text="#{user.age}">年龄</p><button th:text="#{button.submit}">提交</button><!-- 切换语言的链接(通过参数指定 locale) --><a th:href="@{/page(locale=zh_CN)}">中文</a><a th:href="@{/page(locale=en)}">English</a>
      </body>
      </html>
      
    • 步骤 3:配置 SpringBoot 支持国际化

      application.properties 中添加:

      spring.messages.basename=messages
      spring.mvc.locale-resolver=fixed  # 或用 Cookie、Session 方式,根据需求选择
      
  8. 自定义工具类(Dialect 扩展)

    如果内置对象满足不了需求,可自定义 Thymeleaf 工具类,通过 Dialect 扩展语法。

    **示例:**自定义字符串脱敏工具。

    // 自定义工具类
    public class MyUtils {public String maskPhone(String phone) {if (phone == null || phone.length() < 11) return phone;return phone.substring(0, 3) + "****" + phone.substring(7);}
    }// 注册 Dialect
    @Configuration
    public class ThymeleafConfig {@Beanpublic MyDialect myDialect() {return new MyDialect();}
    }class MyDialect extends AbstractProcessorDialect {public MyDialect() {super("My Dialect", "my", 1000);}@Overridepublic Set<IProcessor> getProcessors(String dialectPrefix) {Set<IProcessor> processors = new HashSet<>();processors.add(new MyUtilityExpressionObjectFactory(dialectPrefix));return processors;}
    }class MyUtilityExpressionObjectFactory extends AbstractUtilityExpressionObjectFactory {public MyUtilityExpressionObjectFactory(String dialectPrefix) {super(dialectPrefix);}@Overrideprotected Map<String, Object> createObjectMap() {Map<String, Object> map = new HashMap<>();map.put("myUtils", new MyUtils()); // 注册工具类,页面中通过 ${#myUtils.xxx} 调用return map;}
    }
    
    <!-- 页面中使用自定义工具 -->
    <p>脱敏手机号:<span th:text="${#myUtils.maskPhone('13800138000')}"></span></p>
    
  9. 性能与缓存配置

    在生产环境中,需关注 Thymeleaf 的缓存和性能,可通过配置调整:

    # 开发环境关闭缓存(便于实时看到模板修改效果)
    spring.thymeleaf.cache=false# 生产环境开启缓存(提升性能)
    spring.thymeleaf.cache=true# 模板编码(避免中文乱码)
    spring.thymeleaf.encoding=UTF-8
    
http://www.dtcms.com/a/606523.html

相关文章:

  • Git 命令 作用、常用选项、示例、何时使用与注意事项指南
  • 太原制作网站企业更换网站服务器
  • 深入理解 Python 的属性化方法
  • 北京网站备案拍照的地点河北建设厅网站开通账号
  • AI Agent记忆系统深度实现:从短期记忆到长期人格的演进
  • APScheduler入门:轻松掌握Python任务调度
  • LLMs之 Ranking:OpenRouter LLM Rankings的简介、安装和使用方法、案例应用之详细攻
  • 算法题(Python)链表篇 | 3.翻转链表
  • 找个免费的网站这么难吗用jsp做的二手交易网站
  • 网站后台申请邮箱手机网站 方案
  • 新站突然网站停止收录给公司做个网站多少钱
  • 【C语言实战:实现数组的重复拼接(动态内存+指针参数详解)】
  • wordpress文章付费可看温岭新站seo
  • React zustand todos案例(带本地存储localStorage、persist)todoStore.ts
  • mac配置 unity+vscode的坑
  • 极速网站推广专家wordpress综合网
  • 上海定制网站建设公司网站域名什么意思
  • 【OpenCV + VS】直方图与模糊操作
  • 代码随想录 435.无重叠区间
  • 【AVL树与红黑树】:告别“瘸腿”树,体验平衡的艺术
  • 智慧团建网站入口官网有什么做ppt的网站吗
  • 机器人“小脑”萎缩,何谈“大脑”智慧?六维力/关节力传感器才是“救命稻草”
  • 基于SpringBoot的图书馆管理系统的设计与实现
  • SpringCloud快速通关(中)
  • 性价比高的时序数据库哪个专业
  • 邵阳高端网站建设做响应式网站的物流
  • 网站定制开发哪家厉害网站登录界面源码
  • 自己电脑做网站服务器违法吗上海网站建设最好的公司排名
  • C++-vector-back子函数和std::move函数详细介绍
  • 07.指针