SpringBoot——Thymeleaf模板引擎使用详解
什么是Thymeleaf
Thymeleaf是一个用于web和独立环境的现代服务器端Java模板引擎。Thymeleaf的主要目标是将优雅自然的模板引入到您的开发工作流程中——HTML可以在浏览器中正确显示,也可以作为静态原型工作,从而在开发团队中实现更强大的协作。
有了Spring框架的模块、与您喜爱的工具的大量集成,以及插入您自己的功能的能力,Thymeleaf是现代HTML5 JVM web开发的理想选择——尽管它可以做的还有很多。
如何在自己的项目中使用Thymeleaf
第一步:去https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/using-boot-build-systems.html#using-boot-starter这个网站找到Thymeleaf的对应starter启动器,然后poml.xml文件中的两个关于Thymeleaf的依赖复制下来,粘贴到你项目的pom.xml文件的<dependency>标签下
如下图:
pom.xml
1 <dependency> 2 <groupId>org.thymeleaf</groupId> 3 <artifactId>thymeleaf-spring5</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>org.thymeleaf.extras</groupId> 7 <artifactId>thymeleaf-extras-java8time</artifactId> 8 </dependency>
这里我们的Thymeleaf是基于3.x开发的
第二步:编写Controller类
1 package com.lzp.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.ui.Model; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @Controller 8 public class TemplateController{ 9 10 @RequestMapping("/test") 11 public String template(Model model) { 12 // 存储数据 13 model.addAttribute("msg", "Hello Thymeleaf!!!"); 14 // 返回页面 15 return "template1"; 16 } 17 }
Thymeleaf配置类ThymeleafProperties,之前我们SpringMVC阶段是默认在WEB-INF目录下找.jsp文件,现在是在templates目录下找.html文件
第三步:创建HTML文件测试,注意在没有引入Thymeleaf依赖之前是不能通过Controller控制器来访问templates目录里面的资源
1 <!DOCTYPE html> 2 3 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>测试页面</title> 7 </head> 8 <body> 9 <!--th:text就是将h1中的内容设置为它指定的值,和之前学习的Vue一样--> 10 <h1 th:text="${msg}"></h1> 11 </body> 12 </html>
第四步:启动服务器看前端浏览器访问结果
到此,我们的Thymeleaf模板引擎就介绍完毕了,谢谢大家的支持!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能