1.Thymeleaf简介
- JSP必须依赖Tomcat运行,不能直接运行在浏览器中
- HTML可以直接运行在浏览器中,但是不能接收控制器传递的数据
- Thymeleaf既保留了HTML的后缀能够直接在浏览器运行,又实现了JSP显示动态数据的功能
2.Thymeleaf的使用
SpringBoot对Thymeleaf提供了良好的支持
- 2.1.SpringBoot项目添加Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
-
2.2.创建Thymeleaf模板
Thymeleaf模板就是HTML页面
- 2.2.1.SpringBoot项目中 resources/templates目录就是用来存放页面模板的
💡 static目录下的资源被定义为静态资源,SpringBoot默认不拦截;如果将HTML页面创建在static目录是可以直接访问的
举个例子:
💡 templates目录下的文件被定义为动态网页模板,SpringBoot会拦截templates中定义的资源;如果将HTML页面创建在templates目录,必须通过控制器跳转访问
举个例子:
那么如何访问呢???
- 2.2.1.通常我们需要创建一个PageController类,用于转发页面请求
@Controller
public class PapeController {
@RequestMapping("/index.html")
public String test(Model model){
return "index";
}
}
3.Thymeleaf取值
- 3.1.在Thymeleaf模板页面进入th标签的命名空间
<!DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
-
3.2.标签
- 3.2.1.
th:text
// 几乎所有的HTML标签都可以使用th:text属性,将接收到的数据显示在标签的内容中 <label th:text="${name}"></label> <p th:text="${user.userName}"></p> <div th:text="${user.userName}"></div>
-
3.2.2.
th:inline
内联标签- HTML内联
<p th:inline="text">年龄:[[${user.age}]]</p>
- CSS内联
<style type="text/css" th:inline="css"> .test{ color:[[${color}]] } </style>
- JavaScript内联
<script type="text/css" th:text="javascript"> </script>
-
3.2.3.
th:each
循环控制
<table border="1"> <caption>水果集合</caption> <thead> <tr> <th>水果名称</th> </tr> </thead> <tbody> <tr th:each="s:${strs}"> <td th:text="${s}" class="test"></td> </tr> </tbody> </table>
- 3.2.1.
4.主要代码
PapeController类
@Controller
public class PapeController{
@RequestMapping("/index.html")
public String test(Model model){
// 字符串
model.addAttribute("name","张三");
// CSS内联
model.addAttribute("color","red");
// 自定义对象
User user = new User("李四",25);
model.addAttribute("user",user);
//集合
List<String>strs = new ArrayList<>();
strs.add("苹果");
strs.add("香蕉");
strs.add("西红柿");
model.addAttribute("strs",strs);
return "index";
}
}
User类
@Data
@AllArgsConstructor
public class User{
private String userName;
private int age;
}
index.html页面
<!DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- CSS内联 -->
<style type="text/css" th:inline="css">
.test{
color:[[${color}]]
}
</style>
<!-- javaScript内联 -->
<script type="text/css" th:text="javascript">
</script>
</head>
<body>
姓名:<label th:text="${name}" class="test"></label>
<hr>
姓名:<label th:text="${user.userName}">无</label>
<!-- HTML内联 -->
<p th:inline="text">年龄:[[${user.age}]]</p>
<hr>
<!-- 集合 th:each -->
<table border="1">
<caption>水果集合</caption>
<thead>
<tr>
<th>水果名称</th>
</tr>
</thead>
<tbody>
<tr th:each="s:${strs}">
<td th:text="${s}" class="test"></td>
</tr>
</tbody>
</table>
</body>
</html>