Thymeleaf
Thymeleaf 是一种类似于 JSP 的动态网页技术
1.1 Thymeleaf 简介
- JSP 必须依赖 Tomcat 运行,不能直接运行在浏览器中
- HTML 可以直接运行在浏览器中,但是不能接收控制器传递的数据
- Thymeleaf 是一种既保留了 HTML 的后缀,能够直接在浏览器中运行的能力,又实现了 JSP 显示动态数据的功能——
静能查看页面效果,动则可显示数据
1.2 Thymeleaf 的使用
SpringBoot 应用对 Thymeleaf 提供了良好的支持
-
添加依赖
spring-boot-starter-thymeleaf
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
创建 Thymeleaf 模板
Thymeleaf 模板就是 HTML 文件
SpringBoot 应用中
resoureces\templates
目录就是来存放页面模板
-
说明:
- static 目录下的资源被定义静态资源,SpringBoot 一ing用默认放行;
如果将 HTML 页面创建 static 目录是直接可以访问的
- templates 目录下的文件会被定义为动态网页模板,SpringBoot 应用会拦截 templates 中定义的资源,
如果将 HTML 页面创建 templates 目录,则必须通过控制器跳转访问
- static 目录下的资源被定义静态资源,SpringBoot 一ing用默认放行;
-
在 templates 创建 HTML 页面模板
-
创建 PageController,用于转发允许
直接访问
的页面请求@Controller @RequestMapping("/page") public class PageController{ @RequestMapping("/test.html") public String test(){ return "test"; } }
1.3 Thymeleaf 基本语法
如果要在 thymeleaf 模板中获取从控制器传递的shju’ju,需要使用 th 标签
1.3.1 在 thymeleaf 模板页面引入 th 标签的命名空间
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
</html>
1.3.2 thymeleaf 各种标签用法
-
th:text,在几乎所有的 HTML 双标签都可以使用,
将接收到的属性显示到标签的内容中
<div th:text="${str}"></div>
-
th:inline,内联标签
- HTML 内联
<p th:inline="text">图书名称:[[{book.bookName}]] </p>
-
CSS 内联
<style th:inline="css"> .style1{ color:[[{color}]] } </style>
-
JavaScript 内联
<script type="css/javascript" th:inline="javascript"> </script>
-
**th:object 和 ***,外层用 object 内层 用 *
<div th:object="${book}"> <p th:text="*{bookId}"></p> <p th:text="*{bookName}"></p> <p th:text="*{bookAuthor}"></p> </div>
-
th:each,循环当前标签
<tr th:ecah="b:${books}"> <td th:text="${b.bookId}"></td> <td th:text="${b.bookName}"></td> <td th:text="${b.bookAuthor}"></td> </tr>
-
th:if,分支,判断 ,如果条件不显示,则不显示此标签
<td th:if="${b.bookPrice}>40" style="color:red">太贵!</td>
<td th:if="${b.bookPrice}<40"style="color:green">推荐购买</td>
</tr>
-
**th:switch 和 th:case **
<td th:switch="${b.bookPrice}/10"> <lable th:case="1">建议购买</lable> <lable th:case="2">价格合理</lable> <lable th:case="*"价格不合理</lable> </td>
1.4 Thymeleaf 碎片使用
1.4.1 碎片的概念
碎片,就是 HTML 片段,我们可以将多个页面中使用的相同的 HTML 标签部分单独定义,然后通过 th:include,可以在 HTML 网页中引入定义的碎片
1.4.2 碎片使用案例
- 定义碎片:th:fragment
- 引用碎片:th:include 和 th:replace