SpringBoot Thymeleaf使用教程(实用版)

使用Thymeleaf 三大理由:

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

学习目标

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

快速查阅

专题阅读:《SpringBoot 布道系列》

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

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

官方指南: Thymleaf 3.0 官方教程

相关教程:SpringBoot Thymeleaf 基本介绍SpringBoot 在IDEA中实现热部署(实用版)

使用教程

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

一、基础语法

变量表达式 ${}

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

<form id="userForm">
    <input id="id" name="id" th:value="${user.id}"/>
    <input id="username" name="username" th:value="${user.username}"/>
    <input id="password" name="password" th:value="${user.password}"/>
</form>

<div th:text="hello"></div>

<div th:text="${user.username}"></div>

选择变量表达式 *{}

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

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

<form id="userForm" th:object="${user}">
    <input id="id" name="id" th:value="*{id}"/>
    <input id="username" name="username" th:value="*{username}"/>
    <input id="password" name="password" th:value="*{password}"/>
</form>

链接表达式 @{}

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

<script th:src="@{/webjars/jquery/jquery.js}"></script>
<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 填写片段路径和片段名。例如:

<!-- /views/common/head.html-->
<head th:fragment="static">
        <script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
</head>

<!-- /views/your.html -->
<div th:replace="~{common/head::static}"></div>

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

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

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

消息表达式

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

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

其它表达式

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

<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 即可快速完成迭代。例如遍历用户列表:

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

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

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

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

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

四、条件判断

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

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

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

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

五、日期格式化

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

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

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

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

六、内联写法

  • (1)为什么要使用内联写法?·答:因为 JS无法获取服务端返回的变量。

  • (2)如何使用内联表达式?答:标准格式为:[[${xx}]] ,可以读取服务端变量,也可以调用内置对象的方法。例如获取用户变量和应用路径:

    <script th:inline="javascript">
        var user = [[${user}]];`
        var APP_PATH = [[${#request.getContextPath()}]];
        var LANG_COUNTRY = [[${#locale.getLanguage()+'_'+#locale.getCountry()}]];
    </script>
  • (3)标签引入的JS里面能使用内联表达式吗?答:不能!内联表达式仅在页面生效,因为Thymeleaf只负责解析一级视图,不能识别外部标签JS里面的表达式。

七、国际化

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

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

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

八、详细教程

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

首先通过Spring Initializr创建项目,如图所示:

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

<dependencies>
        <dependency><!--Web相关依赖-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency><!--页面模板依赖-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency><!--热部署依赖-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

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

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

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

@RestController
public class UserController {
    private List<User> userList = new ArrayList<>();
    {
        userList.add(new User("1", "socks", "123456", new Date()));
        userList.add(new User("2", "admin", "111111", new Date()));
        userList.add(new User("3", "jacks", "222222", null));
    }
    @GetMapping("/")
    public ModelAndView index() {
        return new ModelAndView("user/user", "userList", userList);
    }
}

public class User {
    private String id;
    private String username;
    private String password;
    private Date createTime;
    //请读者自行补充 构造器和 get/set方法..
}

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

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

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title th:text="用户信息">User</title>
    <!--默认拼接前缀路径,开头请勿再添加斜杠,防止部署运行报错!-->
    <script th:replace="common/head::static"></script>
</head>
<body>

<div th:each="user,userStat:${userList}" th:class="${userStat.even}?'even':'odd'">
    序号:<input type="text" th:value="${userStat.count}"/>
    账号:<input type="text" th:value="${user.username}"/>
    密码:<input type="password" th:value="${user.password}"/>
    时间:<input type="text" th:value="${user.createTime}"/>
    时间:<input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/>
</div>

<script th:inline="javascript">
    //通过内联表达式获取用户信息
    var userList = [[${userList}]];
    console.log(userList)
</script>
</body>
</html>

然后编写单个用户页面:

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

快速启动项目

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335