在Spring Boot中嵌入Thymeleaf模板引擎(随笔)
1.模板引擎:
是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎会生成一个标准的HTML文档。使用模板引擎的目的就是为了使前后端分离。
2.Thymeleaf
Thymeleaf官网:https://www.thymeleaf.org/
官网解释:Thymeleaf is a modern server-side Java template engine for both web and standalone environments.(翻译:Thymeleaf是一个用于web和独立环境的现代服务器端Java模板引擎。)
Thymeleaf的文件扩展名为.html,是对HTML文件的一种扩展
3.在SpringBoot中嵌入Thymeleaf
1)导入Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)新建一个controller类用于跳转到指定的xx.html页面
@Controller
@RequestMapping("/thymeleaf")
public class OneController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("hello", "Hello Thymeleaf!");
//welcome为Thymeleaf的HTML文件,不需要扩展名
return "welcome";
}
}
3)(注意)在resources/templates目录下新建一个xx.html文件,接收 controller类中传过来的参数
导入命名空间:xmlns:th="http://www.thymeleaf.org/"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/"><!--注意!-->
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body>
<p th:text="${hello}">这里是p标签下显示的数据</p>
<span th:text="${hello}">这里是span标签下显示的数据</span>
<div th:text="${hello}">这里是div标签下显示的数据</div>
</body>
</html>
4)启动服务器,访问页面上只显示hello变量中保存的数据,不显示标签中的文字信息
5)如何查看HTML页面标签中的文字信息
找到项目所在在文件夹,打开src/main/resources/templates目录下新建的 xx.html页面即可查看。