使用Thymeleaf 三大理由:

  1. 简洁漂亮 容易理解
  2. 完美支持HTML5 使用浏览器直接打开页面
  3. 不新增标签 只需增强属性

学习目标

  • 快速掌握Thymeleaf的基本使用:五大基础语法,常用内置对象

快速查阅

源码下载:springboot-web-thymeleaf-enhance

— Hey Man,Don't forget to Star or Fork . —

官方指南:Thymleaf 3.0 官方教程

使用教程

温馨提示:Thymeleaf 最为显著的特征是增强属性,任何属性都可以通过th:xx 来完成交互,例如th:value最终会覆盖value属性。

一、基础语法

变量表达式  ${}

使用方法:直接使用th:xx = "${}" 获取对象属性 。例如:

  1. <form id="userForm">
  2. <input id="id" name="id" th:value="${user.id}"/>
  3. <input id="username" name="username" th:value="${user.username}"/>
  4. <input id="password" name="password" th:value="${user.password}"/>
  5. </form>
  6. <div th:text="hello"></div>
  7. <div th:text="${user.username}"></div>

选择变量表达式 *{}

使用方法:首先通过th:object 获取对象,然后使用th:xx = "*{}"获取对象属性。

这种简写风格极为清爽,推荐大家在实际项目中使用。 例如:

  1. <form id="userForm" th:object="${user}">
  2. <input id="id" name="id" th:value="*{id}"/>
  3. <input id="username" name="username" th:value="*{username}"/>
  4. <input id="password" name="password" th:value="*{password}"/>
  5. </form>

链接表达式 @{}

使用方法:通过链接表达式@{}直接拿到应用路径,然后拼接静态资源路径。例如:

  1. <script th:src="@{/webjars/jquery/jquery.js}"></script>
  2. <link th:href="@{/webjars/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">

片段表达式 ~{}

片段表达式是Thymeleaf的特色之一,细粒度可以达到标签级别,这是JSP无法做到的。

片段表达式拥有三种语法:

  • ~{ viewName } 表示引入完整页面
  • ~{ viewName ::selector} 表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等
  • ~{ ::selector} 表示在当前页寻找

使用方法:首先通过th:fragment定制片段 ,然后通过th:replace 填写片段路径和片段名。例如:

  1. <!-- /views/common/head.html-->
  2. <head th:fragment="static">
  3. <script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
  4. </head>
  5. <!-- /views/your.html -->
  6. <div th:replace="~{common/head::static}"></div>

在实际使用中,我们往往使用更简洁的表达,去掉表达式外壳直接填写片段名。例如:

  1. <!-- your.html -->
  2. <div th:replace="common/head::static"></div>

值得注意的是,使用替换路径th:replace 开头请勿添加斜杠,避免部署运行的时候出现路径报错。(因为默认拼接的路径为spring.thymeleaf.prefix = classpath:/templates/

消息表达式

即通常的国际化属性:#{msg} 用于获取国际化语言翻译值。例如:

  1. <title th:text="#{user.title}"></title>

其它表达式

在基础语法中,默认支持字符串连接、数学运算、布尔逻辑和三目运算等。例如:

  1. <input name="name" th:value="${'I am '+(user.name!=null?user.name:'NoBody')}"/>

二、内置对象

官方文档:附录A: Thymeleaf 3.0 基础对象

官方文档:附录B: Thymeleaf 3.0 工具类

七大基础对象:

  • ${#ctx} 上下文对象,可用于获取其它内置对象。
  • ${#vars}: 上下文变量。
  • ${#locale}:上下文区域设置。
  • ${#request}: HttpServletRequest对象。
  • ${#response}: HttpServletResponse对象。
  • ${#session}: HttpSession对象。
  • ${#servletContext}: ServletContext对象。

常用的工具类:

  • #strings:字符串工具类
  • #lists:List 工具类
  • #arrays:数组工具类
  • #sets:Set 工具类
  • #maps:常用Map方法。
  • #objects:一般对象类,通常用来判断非空
  • #bools:常用的布尔方法。
  • #execInfo:获取页面模板的处理信息。
  • #messages:在变量表达式中获取外部消息的方法,与使用#{...}语法获取的方法相同。
  • #uris:转义部分URL / URI的方法。
  • #conversions:用于执行已配置的转换服务的方法。
  • #dates:时间操作和时间格式化等。
  • #calendars:用于更复杂时间的格式化。
  • #numbers:格式化数字对象的方法。
  • #aggregates:在数组或集合上创建聚合的方法。
  • #ids:处理可能重复的id属性的方法。

三、迭代循环

想要遍历List集合很简单,配合th:each 即可快速完成迭代。例如遍历用户列表:

  1. <div th:each="user:${userList}">
  2. 账号:<input th:value="${user.username}"/>
  3. 密码:<input th:value="${user.password}"/>
  4. </div>

在集合的迭代过程还可以获取状态变量,只需在变量后面指定状态变量名即可,状态变量可用于获取集合的下标/序号、总数、是否为单数/偶数行、是否为第一个/最后一个。例如:

  1. <div th:each="user,stat:${userList}" th:class="${stat.even}?'even':'odd'">
  2. 下标:<input th:value="${stat.index}"/>
  3. 序号:<input th:value="${stat.count}"/>
  4. 账号:<input th:value="${user.username}"/>
  5. 密码:<input th:value="${user.password}"/>
  6. </div>

如果缺省状态变量名,则迭代器会默认帮我们生成以变量名开头的状态变量 xxStat, 例如:

  1. <div th:each="user:${userList}" th:class="${userStat.even}?'even':'odd'">
  2. 下标:<input th:value="${userStat.index}"/>
  3. 序号:<input th:value="${userStat.count}"/>
  4. 账号:<input th:value="${user.username}"/>
  5. 密码:<input th:value="${user.password}"/>
  6. </div>

四、条件判断

条件判断通常用于动态页面的初始化,例如:

  1. <div th:if="${userList}">
  2. <div>的确存在..</div>
  3. </div>

如果想取反则使用unless 例如:

  1. <div th:unless="${userList}">
  2. <div>不存在..</div>
  3. </div>

五、日期格式化

使用默认的日期格式(toString方法) 并不是我们预期的格式:Mon Dec 03 23:16:50 CST 2018

  1. <input type="text" th:value="${user.createTime}"/>

此时可以通过时间工具类#dates来对日期进行格式化:2018-12-03 23:16:50

  1. <input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/>

六、内联写法

  • (1)为什么要使用内联写法?·答:因为 JS无法获取服务端返回的变量。
  • (2)如何使用内联表达式?答:标准格式为:[[${xx}]] ,可以读取服务端变量,也可以调用内置对象的方法。例如获取用户变量和应用路径:
  1. <script th:inline="javascript">
  2. var user = [[${user}]];`
  3. var APP_PATH = [[${#request.getContextPath()}]];
  4. var LANG_COUNTRY = [[${#locale.getLanguage()+'_'+#locale.getCountry()}]];
  5. </script>
  • (3)标签引入的JS里面能使用内联表达式吗?答:不能!内联表达式仅在页面生效,因为Thymeleaf只负责解析一级视图,不能识别外部标签JS里面的表达式。

七、国际化

需要了解更多关于国际化的精彩描述请前往 SpringBoot 快速实现国际化i18n 。

例如在国际化文件中编写了user.title这个键值,然后使用#{}读取这个KEY即可获取翻译。

  1. <title th:text="#{user.title}">用户登陆</title>

八、详细教程

======== 有了上述基础后 下面正式开始Thymeleaf 的详细教程 ==============

首先通过Spring Initializr创建项目,

然后在POM文件引入web 、thymeleaf等依赖

  1. <dependencies>
  2. <dependency><!--Web相关依赖-->
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency><!--页面模板依赖-->
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  9. </dependency>
  10. <dependency><!--热部署依赖-->
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-devtools</artifactId>
  13. <scope>runtime</scope>
  14. </dependency>
  15. </dependencies>

然后在src/main/resources/application.yml 配置页面路径:

  1. spring:
  2. thymeleaf:
  3. cache: false #关闭缓存
  4. prefix: classpath:/views/ #调整页面路径

接着在src/main/java/com/hehe/web/UserController 获取用户信息:

  1. @RestController
  2. public class UserController {
  3. private List<User> userList = new ArrayList<>();
  4. {
  5. userList.add(new User("1", "socks", "123456", new Date()));
  6. userList.add(new User("2", "admin", "111111", new Date()));
  7. userList.add(new User("3", "jacks", "222222", null));
  8. }
  9. @GetMapping("/")
  10. public ModelAndView index() {
  11. return new ModelAndView("user/user", "userList", userList);
  12. }
  13. }
  14. public class User {
  15. private String id;
  16. private String username;
  17. private String password;
  18. private Date createTime;
  19. //请读者自行补充 构造器和 get/set方法..
  20. }

开始编写公共页面:src/main/resources/views/common/head.html ,其中static为页面片段:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <!--声明static为页面片段名称-->
  4. <head th:fragment="static">
  5. <link th:href="@{/webjars/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css"/>
  6. <script th:src="@{/webjars/jquery/jquery.js}"></script>
  7. </head>
  8. </html>

接着编写用户列表页:src/main/resources/views/user/user.html 配合th:each显示用户列表信息。

使用说明:这里 th:replace="common/head::static" 表示将引用${spring.thymeleaf.prefix}/common/head.htmlstatic页面片段,值得注意的是由于替换路径默认会拼接前缀路径,所以开头切勿在添加斜杠,否则在打包成JAR部署运行时将提示报Templates not found... 。

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title th:text="用户信息">User</title>
  6. <!--默认拼接前缀路径,开头请勿再添加斜杠,防止部署运行报错!-->
  7. <script th:replace="common/head::static"></script>
  8. </head>
  9. <body>
  10. <div th:each="user,userStat:${userList}" th:class="${userStat.even}?'even':'odd'">
  11. 序号:<input type="text" th:value="${userStat.count}"/>
  12. 账号:<input type="text" th:value="${user.username}"/>
  13. 密码:<input type="password" th:value="${user.password}"/>
  14. 时间:<input type="text" th:value="${user.createTime}"/>
  15. 时间:<input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/>
  16. </div>
  17. <script th:inline="javascript">
  18. //通过内联表达式获取用户信息
  19. var userList = [[${userList}]];
  20. console.log(userList)
  21. </script>
  22. </body>
  23. </html>

然后编写单个用户页面:


至此大功告成,然后快速启动项目,如图所示:

快速启动项目

然后访问用户列表: http://localhost:8080,如图所示

然后访问单个用户: http://localhost:8080/user/1,如图所示:

SpringBoot与Thymeleaf入门级操作的更多相关文章

  1. 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础授权权限

    上一篇<[原]无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限>介绍了实现Shiro的基础认证.本篇谈谈实现 ...

  2. 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限

    开发环境搭建参见<[原]无脑操作:IDEA + maven + SpringBoot + JPA + Thymeleaf实现CRUD及分页> 需求: ① 除了登录页面,在地址栏直接访问其他 ...

  3. Springboot+JPA+Thymeleaf 校园博客完整小网站

    本文所属[知识林]:http://www.zslin.com/web/article/detail/35 此项目是一个比较简易的校园博客.麻雀虽小五脏俱全,虽然是比较简易的但是涉及的知识点还是比较全面 ...

  4. 从.Net到Java学习第九篇——SpringBoot下Thymeleaf

    从.Net到Java学习系列目录 Thymeleaf概述 Thymeleaf 是一个流行的模板引擎,该模板引擎采用java语言开发.模板引擎是一个技术名称,是跨领域平台的概念,在java语言体系下有模 ...

  5. IDEA上创建 Maven SpringBoot+mybatisplus+thymeleaf 项目

    概述 在WEB领域,Java也是在不断的探索和改进,从开始的JSP--->Struts1--->Struts2+Spring--->Spring MVC--->SpringBo ...

  6. springboot引入thymeleaf

    springboot引入thymeleaf 1.Thymeleaf使用 @ConfigurationProperties(prefix = "spring.thymeleaf") ...

  7. SpringBoot入坑-持久化操作

    前面内容中我们已经了解到了SpringBoot关于参数传递的相关知识,本篇我们一起来学习一下SpringBoot关于数据库持久化操作的知识,这里我们使用JPA进行数据库的持久化操作. 首先由于我们需要 ...

  8. 【Springboot】Springboot整合Thymeleaf模板引擎

    Thymeleaf Thymeleaf是跟Velocity.FreeMarker类似的模板引擎,它可以完全替代JSP,相较与其他的模板引擎,它主要有以下几个特点: 1. Thymeleaf在有网络和无 ...

  9. 从.Net到Java学习第六篇——SpringBoot+mongodb&Thymeleaf&模型验证

    SpringBoot系列目录 SpringBoot整合mongodb MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.如果你没用过Mong ...

  10. SpringBoot 之Thymeleaf模板.

    一.前言 Thymeleaf 的出现是为了取代 JSP,虽然 JSP 存在了很长时间,并在 Java Web 开发中无处不在,但是它也存在一些缺陷: 1.JSP 最明显的问题在于它看起来像HTML或X ...

随机推荐

  1. 对于Vue3和Ts的心得和思考

    作者:京东物流 吴云阔 1 前言 Vue3已经正式发布了一段时间了,各种生态已经成熟.最近使用taro+vue3重构冷链的小程序,经过了一段时间的开发和使用,有了一些自己的思考. 总的来说,Vue3无 ...

  2. 我对vue3的理解

    我对 reactive源码的理解 reactive 只能够代理对象 首先它判断传递过来的值是否是对象,如果是才会进行代理.变成响应式的. Proxy 并没有重写对象的属性,只做代理,在取值的时候回调用 ...

  3. echarts第二次渲染不出来的原因

    场景描述 echarts主要用于数据可视化展示 有些时候,我们可能会根据不同的条件,在页面上进行显示和隐藏. 比如说:页面最初展示了数据,当我点击不同的按钮的时候. echarts会对应的展示或者隐藏 ...

  4. KubeSphere2.1踩坑记

    至少两台机器.推荐4X16.(完全安装KubeSphere会吃掉10G+内存) k8s安装(略1.14.8)可参考我上一篇文章或者基于kubeadmin快速安装 KubeSphere2.1前置条件 1 ...

  5. 洛谷P3101 题解

    输入格式 第 \(1\) 行,三个整数 \(m,n,t\). 第 \(2\) 到 \(m+1\) 行,\(m\) 个整数,表示海拔高度. 第 \(2+m\) 到 \(2m+1\) 行,\(m\) 个整 ...

  6. 关于git的几点疑问

    git rename后查看之前的记录 对于某个文件进行rename之后,使用show log命令查看之前的修改记录都会丢失,通过命令行方式进行mv之后,在tortoisegit中查看记录还是丢失的 g ...

  7. 大语言模型的预训练[3]之Prompt Learning:Prompt Engineering、Answer engineering、Multi-prompt learning、Training strategy详解

    大语言模型的预训练[3]之Prompt Learning:Prompt Engineering.Answer engineering.Multi-prompt learning.Training st ...

  8. C# WinForm 界面控件

    C# WinForm是一种GUI应用程序框架,它允许开发人员使用各种控件来创建丰富的用户界面.以下是一些C# WinForm中常见的界面控件:这些界面控件在C# WinForm应用程序开发中非常常见, ...

  9. 7000字详解Spring Boot项目集成RabbitMQ实战以及坑点分析

    本文给大家介绍一下在 Spring Boot 项目中如何集成消息队列 RabbitMQ,包含对 RibbitMQ 的架构介绍.应用场景.坑点解析以及代码实战.最后文末有免费领取龙年红包封面以及腾讯云社 ...

  10. Windows XP Professional with Service Pack 3 (x86)

    Windows XP Professional with Service Pack 3 (x86) 链接:https://pan.baidu.com/s/1p99vLx5psoq9K4ONlRpkZA ...