一、简介
-
Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎
-
Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和 Freemarker 等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。
Thymeleaf的特点
-
动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
-
开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
-
多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
-
与SpringBoot完美整合,SpringBoot提供了Thymeleaf 的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。
二、使用 Thymeleaf 。
thymelead 必须通过Controller跳转,不能直接访问。
添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Spring Boot默认存放模板页面的路径在src/main/resources/templates
或者src/main/view/templates
,
这个无论是使用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html
。
数据显示:
在MVC的开发过程中,我们经常需要通过Controller
将数据传递到页面中,让页面进行动态展示。
1、显示普通文本
创建一个Controller对象,在其中进行参数的传递
@RequestMapping("/company/index") public String companyIndex(Model model) { model.addAttribute("name","中石化"); model.addAttribute("address","中国北京"); return "companyIndex"; }
<html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <title>111111111111</title> </head> <body> <p th:text="${name}"></p> <p th:text="${address}"></p> </body> </html>
可以看到在p
标签中有th:text
属性,这个就是thymeleaf的语法,它表示显示一个普通的文本信息。
th:utext
中还能做一些基础的数学运算:<p th:text="'数学计算:1+2=' + (1 + 2)"/>
2、显示带有样式的普通文本
如果我们想要传递到的页面的信息,它本身是带有CSS样式的,这个时候如何在页面中将携带的样式信息也显示出来?
此时页面中需要借助th:utext
属性进行显示
1 2 3 4 5 | @RequestMapping ( "/company/index" ) public String companyIndex(Model model) { model.addAttribute( "msg" , "<span style=\"color:red\">这是企业首页<span>" ); return "companyIndex" ; } |
<p th:utext="${msg}"></p>
3、显示对象
我们常常需要将一个bean 信息展示在前端页面当中。
@RequestMapping("/company/index") public String companyIndex(Model model) { CompanyModel companyModel=new CompanyModel(); companyModel.setCompanyCode("10086"); companyModel.setCompanyName("中国移动"); companyModel.setAddress("中国"); companyModel.setAddTime(new Date()); model.addAttribute("vo",companyModel); return "companyIndex"; }
前端html:
<html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <title>111111111111</title> </head> <body> <table> <tr> <th>编号</th> <th>企业名称</th> <th>地址</th> </tr> <!--第一种展示方式--> <tr> <td><p th:text="${vo.companyCode}"></p></td> <td><p th:text="${vo.companyName}"></p></td> <td><p th:text="${vo.address}"></p></td> <td><p th:text="${#dates.format(vo.addTime,'yyyy-MM-dd')}"></p></td> </tr> <!--第一种展示方式--> <tr th:object="${vo}"> <td><p th:text="*{companyCode}"></p></td> <td><p th:text="*{companyName}"></p></td> <td><p th:text="*{address}"></p></td> <td><p th:text="*{#dates.format(addTime,'yyyy-MM-dd')}"></p></td> </tr> </table> </body> </html>
上面给出了两种展现方式,一种是通过${属性},另外一种是通过{属性}。
关于“ ${属性} ”和 “ {属性}” 的区别?
$ 访问完整信息,而访问指定对象中的属性内容, 如果访问的只是普通的内容两者没有区别
4、数据处理
在 thymeleaf 之中提供有相应的集合的处理方法,
例如:在使用 List 集合的时候可以考虑采用 get()方法获取指定索引的数据,那么在使用 Set 集合的时候会考虑使用 contains()来判断某个数据是否存在,
使用 Map 集合的时候也希望可以使用 containsKey()判断某个 key 是否存在,以及使用get()根据 key 获取对应的 value,而这些功能在之前并不具备,
下面来观察如何在页面中使用此类操作
@RequestMapping(value = "/user/set", method = RequestMethod.GET) public String set(Model model) { Set<String> allNames = new HashSet<String>() ; List<Integer> allIds = new ArrayList<Integer>() ; for (int x = 0 ; x < 5 ; x ++) { allNames.add("boot-" + x) ; allIds.add(x) ; } model.addAttribute("names", allNames) ; model.addAttribute("ids", allIds) ; model.addAttribute("mydate", new java.util.Date()) ; return "user_set" ; }
<body> <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"/> <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss.SSS')}"/> <hr/> <p th:text="${#strings.replace('www.baidu.cn','.','$')}"/> <p th:text="${#strings.toUpperCase('www.baidu.cn')}"/> <p th:text="${#strings.trim('www.baidu.cn')}"/> <hr/> <p th:text="${#sets.contains(names,'boot-0')}"/> <p th:text="${#sets.contains(names,'boot-9')}"/> <p th:text="${#sets.size(names)}"/> <hr/> <p th:text="${#sets.contains(ids,0)}"/> <p th:text="${ids[1]}"/> <p th:text="${names[1]}"/> </body>
5、路径处理
在传统WEB工程开发时,路径的处理操作是有点麻烦的。SpringBoot中为我们简化了路径的处理。
在"src/main/view/static/js"中创建一个js文件

<script type="text/javascript" th:src="@{/js/main.js}"></script>
页面之间的跳转也能通过@{}来实现
<a th:href="@{/show}">访问controller方法</a> <a th:href="@{/static_index.html}">访问静态页面</a>
6、操作内置对象
虽然在这种模版开发框架里面是不提倡使用内置对象的,但是很多情况下依然需要使用内置对象进行处理,所以下面来看下如何在页面中使用JSP内置对象。
在控制器里面增加一个方法,这个方法将采用内置对象的形式传递属性。
@RequestMapping(value = "/inner", method = RequestMethod.GET) public String inner(HttpServletRequest request, Model model) { request.setAttribute("requestMessage", "springboot-request"); request.getSession().setAttribute("sessionMessage", "springboot-session"); request.getServletContext().setAttribute("applicationMessage", "springboot-application"); model.addAttribute("url", "www.baidu.cn"); request.setAttribute("url2", "<span style='color:red'>www.baidu.cn</span>"); return "show_inner"; }
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>SpringBoot模版渲染</title> <script type="text/javascript" th:src="@{/js/main.js}"></script> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> </head> <body> <p th:text="${#httpServletRequest.getRemoteAddr()}"/> <p th:text="${#httpServletRequest.getAttribute('requestMessage')}"/> <p th:text="${#httpSession.getId()}"/> <p th:text="${#httpServletRequest.getServletContext().getRealPath('/')}"/> <hr/> <p th:text="'requestMessage = ' + ${requestMessage}"/> <p th:text="'sessionMessage = ' + ${session.sessionMessage}"/> <p th:text="'applicationMessage = ' + ${application.applicationMessage}"/> </body> </html>
7、逻辑处理
所有的页面模版都存在各种基础逻辑处理,
例如:判断、循环处理操作。在 Thymeleaf 之中对于逻辑可以使用如下的一些运算符来完成,
例如:and、or、关系比较(>、<、>=、<=、==、!=、lt、gt、le、ge、eq、ne)。
通过控制器传递一些属性内容到页面之中:
<span th:if="${member.age lt 18}"> 未成年人! </span> <span th:if="${member.name eq '啊三'}"> 欢迎小三来访问! </span>
不满足条件的判断
<span th:unless="${member.age gt 18}"> 你还不满18岁,不能够看电影! </span>
通过swith进行分支判断
<span th:switch="${member.uid}"> <p th:case="100">uid为101的员工来了</p> <p th:case="99">uid为102的员工来了</p> <p th:case="*">没有匹配成功的数据!</p> </span>
8、数据遍历
在实际开发过程中常常需要对数据进行遍历展示,一般会将数据封装成 list 或 map 传递到页面进行遍历操作。
定义控制器类,向页面传递List数据和Map数据

@Controller public class UserController { @RequestMapping(value = "/user/map", method = RequestMethod.GET) public String map(Model model) { Map<String,User> allMembers = new HashMap<String,User>(); for (int x = 0; x < 10; x++) { User vo = new User(); vo.setUid(101L + x); vo.setName("赵四 - " + x); vo.setAge(9); vo.setSalary(99999.99); vo.setBirthday(new Date()); allMembers.put("mldn-" + x, vo); } model.addAttribute("allUsers", allMembers); return "user_map"; } @RequestMapping(value = "/user/list", method = RequestMethod.GET) public String list(Model model) { List<User> allMembers = new ArrayList<User>(); for (int x = 0; x < 10; x++) { User vo = new User(); vo.setUid(101L + x); vo.setName("赵四 - " + x); vo.setAge(9); vo.setSalary(99999.99); vo.setBirthday(new Date()); allMembers.add(vo) ; } model.addAttribute("allUsers", allMembers); return "user_list"; } }
list类型数据遍历

<body> <table> <tr><td>No.</td><td>UID</td><td>姓名</td><td>年龄</td><td>偶数</td><td>奇数</td></tr> <tr th:each="user,memberStat:${allUsers}"> <td th:text="${memberStat.index + 1}"/> <td th:text="${user.uid}"/> <td th:text="${user.name}"/> <td th:text="${user.age}"/> <td th:text="${memberStat.even}"/> <td th:text="${memberStat.odd}"/> </tr> </table> </body>
map类型数据遍历

<body> <table> <tr><td>No.</td><td>KEY</td><td>UID</td><td>姓名</td><td>年龄</td><td>偶数</td><td>奇数</td></tr> <tr th:each="memberEntry,memberStat:${allUsers}"> <td th:text="${memberStat.index + 1}"/> <td th:text="${memberEntry.key}"/> <td th:text="${memberEntry.value.uid}"/> <td th:text="${memberEntry.value.name}"/> <td th:text="${memberEntry.value.age}"/> <td th:text="${memberStat.even}"/> <td th:text="${memberStat.odd}"/> </tr> </table> </body>
9、页面引入
我们常常需要在一个页面当中引入另一个页面,例如,公用的导航栏以及页脚页面。thymeleaf中提供了两种方式进行页面引入。
- th:replace
- th:include
新建需要被引入的页面文件,路径为"src/main/view/templates/commons/footer.html"
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <footer th:fragment="companyInfo"> <p>设为首页 ©2018 SpringBoot 使用<span th:text="${projectName}"/>前必读 意见反馈 京ICP证030173号 </p> </footer>
可以看到页面当中还存在一个变量projectName,这个变量的值可以在引入页面中通过th:with="projectName=百度"
传过来。
引入页面中只需要添加如下代码即可
<div th:include="@{/commons/footer} :: companyInfo" th:with="projectName=百度"/>
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决