Thymeleaf是一款模板引擎,类似于jsp等,主要是能够直接在浏览器中打开并正确显示模板页面,不需要启动整个Web应用,下面介绍如何整合到Spring Boot中
1.添加Thymeleaf模板引擎
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.templates下引入html
注意要引入xmlns:th="http://www.thymeleaf.org"命名空间
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="${name}">静态显示信息a</p>
<div th:text="${age}">静态显示信息b</div>
</body>
</html>
3.定义controller
这样启动项目即可看到效果
4.Thymeleaf常用语法
- 变量表达式${...}:获取变量一般是属性中th:text接收
- *{...}:一般是th:object="${对象}",然后子标签中用th:text="*{对象的属性}",当然也可以直接th:text="*{对象.属性}"
- @{...}形式
- 1)@{'http:......'}:表示绝对地址
- 2)@{|/......|}:有/开头表示相对地址,浏览器会自动加上项目上下文路劲
- 3)@{|......|}:无/开头表示相对地址,浏览器会不会自动加上项目上下文路劲
Thymeleaf语法很多,直接可以查看官网文档即可。