1、引入thymeleaf
在pom.xml中写入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、thymeleaf语法
HelloController.java
package com.gong.springbootcurd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
public class HelloController {
@RequestMapping("/login")
public String success(Map<String,Object> map){
map.put("hello","你好");
return "success";
}
}
thymeleaf会默认访问classpath:/templates/下的html文件,因此发送/login请求时会返回/templates/success.html
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h4>success page</h4>
<div th:text="${hello}">
</div>
</body>
</html>
(1)th:任意html属性;来替换原来属性的值
比如说th:id="
(2)th中的属性是有优先级的
th后面可以接:片段包含、遍历、条件判断、声明变量、属性修改、修改指定属性默认值、修改标签体内容、声明片段等等的属性。
(3)表达式语法
${...}:用于获取变量值(不仅可以获取对象的属性,还可以调用方法、使用内置的基本对象、使用工具对象)
*{...}:选择表达式(和${...}基本功能一致),可以配合th:object使用,简化写法
#{...}:用于获取国际化内容的
@{...}:定义url链接的
~{...}:片段引用表达式
表达式里面可以使用:字面量、文本操作、数学运算、布尔运算、比较运算、条件运算、三元运算符
简略看看其中的一些:
HelloController.java
package com.gong.springbootcurd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
import java.util.Map;
@Controller
public class HelloController {
@RequestMapping("/login")
public String success(Map<String,Object> map){
map.put("hello","<h1>你好<h1>");
map.put("users", Arrays.asList("张三","李四","王五"));
return "success";
}
}
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h4>success page</h4>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<h4 th:text="${user}" th:each="user:${users}"></h4>
<hr/>
<h4>
<span th:each="user:${users}">[[${user}]]</span>
</h4>
</body>
</html>
说明:
th:text:会转义特殊字符
th:utext:不会转义特殊字符
th:each写在h4标签中,每次遍历都会生成一个h4标签。
th:each写在h4标签下的span标签中,每次遍历生成一个span标签。
在文中中获取变量的值要加上两个方括号:[[]]
运行之后查看效果: