1、Thymeleaf简介
SpringBoot推荐使用Thymeleaf替代Jsp。Tymeleaf是一款用于渲染XML/XHTML/HTML5内容的模版引擎,Tymeleaf最大的特点是能够直接在浏览器中打开并正确显示模版页面,而不需要启动整个Web应用。Tymeleaf使用了自然的模版技术,其模版语法并不会破坏文档的结构,Tymeleaf会在运行期替换掉静态值,模版依旧是有效的XML文档。
下面的代码示例分别使用 Velocity、FreeMarker 与 Thymeleaf 打印出一条消息:
Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>
注意,由于 Thymeleaf 使用了 XML DOM 解析器,因此它并不适合于处理大规模的 XML 文件。
2、Thymeleaf的使用
1)引入Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)SpringBoot已经为我们自动配置好了thymeleaf,所有配置值都在 ThymeleafProperties.class直接使用即可。
默认只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染。使用时必须在页面引入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
创建index.html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>[[${title}]]</title>
</head>
<body>
<h1 th:text="${title}"></h1>
<div th:text="${info}">这里的文本之后将会被覆盖</div>
</body>
</html>
3)在Controller中准备数据
package com.example.springboot_demo.controller;
import com.example.springboot_demo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
@GetMapping("/index")
public String ht(Model model){
model.addAttribute("title","hello thymeleaf").addAttribute("info","this is frist thymeleaf page");
return "index";
}
}
页面开发使用@Controller
注解即可,至此整合Thymeleaf完成启动项目。
4)语法规则
th:text
--> 改变当前元素里面的文本内容;
th:任意html属性
--> 来替换原生属性的值
属性优先级:
更多配置参考官方文档:https://www.thymeleaf.org/documentation.html
中文参考书册:https://www.lanzous.com/i7dzr2j