[TOC]

1. Thymeleaf 简介

Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎,甚至在JavaScript中也会用到模板引擎技术,Java生态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。Thymeleaf模板既能用于web环境下,也能用于非web环境下,在非web环境下,它能直接显示模板上的静态数据,在web环境下,它能像JSP一样从后台接收数据并替换掉模板上的静态数据。Thymeleaf 它是基于HTML的,以HTML标签为载体,Thymeleaf 要寄托在HTML的标签下实现对数据的展示,Thymeleaf的官方网站:http://www.thymeleaf.org,Spring boot 集成了thymeleaf模板技术,并且spring boot官方也推荐使用thymeleaf来替代JSP技术,thymeleaf是另外的一种模板技术,它本身并不属于springboot,springboot只是很好地集成这种模板技术,作为前端页面的数据展示。

2. SpringBoot集成Thymeleaf

2.1 在SpringBoot中使用Thymeleaf模板引擎,添加依赖

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

2.2 配置缓存

#开发阶段,建议关闭thymeleaf的缓存
spring.thymeleaf.cache=false

2.3 写一个Controller去映射到模板页面

@RequestMapping("/index")
public String index (Model model) {
    model.addAttribute("data", "恭喜,Spring boot集成 Thymeleaf成功!");
    //return 中就是你页面的名字(不带.html后缀)
    return "index";
}

2.4 编写HTML并加入依赖

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Spring boot集成 Thymeleaf</title>
</head>
  <body>
         <p th:text="${data}">Spring boot集成 Thymeleaf</p>
  </body>
</html>

3. Thymeleaf语法

3.1 Thymeleaf 的标准表达式

准备一个实体类,用于测试

@RequestMapping(value="/userinfo")
public String userinfo (Model model) {
    User user = new User();
    user.setId(1);
    user.setNick("昵称");
    user.setPhone("13700020000");
    user.setAddress("北京朝阳区");
    model.addAttribute("user", user);
    model.addAttribute("hello", "helloworld");
    return "user";
}

3.1.1 标准变量表达式

语法:${…},变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和 JSTL 中的 ${} 相同,Thymeleaf 中的变量表达式使用 ${变量名} 的方式获取其中的数据,比如在Spring mvc 的 Controllar中使用model.addAttribute向前端传输数据

<td th:text="${user.nick}">x</td>
<td th:text="${user.phone}">137xxxxxxxx</td>
<td th:text="${user.email}">xxx@xx.com</td>
<td th:text="${user.address}">北京.xxx</td>
<span th:text="${hello}">你好</span>

3.1.2 选择变量表达式

语法:*{…},选择变量表达式,也叫星号变量表达式,使用 th:object 属性来绑定对象,比如:

<div th:object="${user}" >
    <p>nick: <span th:text="*{nick}">张</span></p>
    <p>phone: <span th:text="*{phone}" >三</span></p>
    <p>email: <span th:text="*{email}" >北京</span></p>
    <p>address: <span th:text="*{address}" >北京</span></p>
</div>

3.1.3 URL表达式

语法:@{…},URL表达式可用于