什么是Thymeleaf
- 在SSM中我们经常使用的是jsp文件实现视图来动态的获取后端传来的数据, 但是在SpringBoot中项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。
- SpringBoot推荐你可以来使用模板引擎:
- 其实jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的, 只是Thymeleaf更适合SpringBoot项目
模板引擎的原理
- 模板引擎的原理就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。主要来介绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他的这个语法更简单。而且呢,功能更强大。
ThymeLeaf的使用
- 使用SpringBoot项目无论什么功能, 都是一个start启动器的事情, 所以我们导入启动器依赖
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 我们去找一下Thymeleaf的自动配置类:ThymeleafProperties
- 我们会发现这个配置其实就是实现视图解析器的配置, 他的前缀prefix是classpath:/templates他的后缀是.html文件
- 得出结论我们应该把我们的XX.html文件放在这个路径下, 并且是只有经过这个javaConfig配置的视图解析器才可以访问到
Thymeleaf的语法
- ThymeLeaf的语法也是很少的, 他的基本思路就是所有的html元素都可以被thymeleaf替换接管 th:[元素名]
- 官方文档: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax
- 在第四章和第十章比较重要
- 简单表达式:
变量表达式: ${…}
选择变量表达式: *{…}
消息表达: #{…}
链接URL表达式: @{…}
片段表达式: ~{…} - 文字
文本文字:‘one text’,‘Another one!’,…
号码文字:0,34,3.0,12.3,…
布尔文字:true,false
空文字: null
文字标记:one,sometext,main,… - 文字操作:
字符串串联: +
文字替换: |The name is ${name}| - 算术运算:
二元运算符:+,-,*,/,%
减号(一元运算符): - - 布尔运算:
二元运算符:and,or
布尔否定(一元运算符): !,not - 比较和平等:
比较:>,<,>=,<=(gt,lt,ge,le)
等号运算符:==,!=(eq,ne) - 条件运算符:
如果-则: (if) ? (then)
如果-则-否则: (if) ? (then) : (else)
默认: (value) ?: (defaultvalue) - 特殊令牌:
无操作: _
测试
- 在templates下的html文件还要有一点就是要导入对应的Thymeleaf约束
xmlns:th="http://www.thymeleaf.org"
@Controller
public class HelloController {
@RequestMapping("/h1")
public String test(Model model) {
model.addAttribute("msg", "hello SpringBoot");
model.addAttribute("p", "<p>我是p标签中的内容</p>");
model.addAttribute("list", Arrays.asList("one", "two", "three"));
return "test";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>test页面</p>
<div th:text="${msg}" ></div>
<!--使用text转义特殊字符-->
<div th:text="${p}"></div>
<div th:utext="${p}"></div>
<div th:each="num:${list}" th:text="${num}" ></div>
<p>===================</p>
<div th:each="num:${list}">[[${num}]]</div>
</body>
</html>