ch10-Thymeleaf 模板引擎01
1.1 认识 Thymeleaf
Thymeleaf:是使用java开发的模板技术,在服务器端运行。把处理后的数据发送给浏览器。模板是作视图层工作的,显示数据的。Thymeleaf 是基于 Html 语言。Thymleaf 语法是应用在 html 标签中。SpringBoot框架集成 Thymealeaf,使用 Thymeleaf 代替 jsp 。
Thymeleaf 的官方网站:http://www.thymeleaf.org
Thymeleaf 官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
1.2 SpringBoot 集成 Thymeleaf
1.2.1 Maven 依赖
<dependencies>
<!--模版引擎依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--web 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
1.2.2 创建模版文件
在 resources/templates/目录下创建 demo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>第一个例子</title>
</head>
<body>
<table>
<tr><td>测试数据</td></tr>
<tr><td th:text="${data}">demo</td></tr>
<tr><td th:text="${mydata}">10086</td></tr>
</table>
</body>
</html>
1.2.3 创建 Controller
package com.suyv.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ThymeleafController {
@GetMapping("/demo")
public String demo(Model model,HttpServletRequest request){
// 添加数据到request作用域,模板引擎可以从request中获取数据
request.setAttribute("data","欢迎使用Thymeleaf模板");
model.addAttribute("mydata","182");
// 指定视图
return "demo";
}
}