首先我们用SpringBoot创建一个支持thymeleaf的web项目
添加web支持
添加thymeleaf模板引擎
创建好该项目之后,在templates目录下创建一个普通的html文件,这个时候只需要写一个controller就可以实现页面的跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello thymeleaf
</body>
</html>
package com.hzy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("test")
public String test() {
return "test";
}
}
这样可以实现了页面的跳转,但是thymeleaf还没有发力,也就是说,现在写的只是html代码,要想用到thymeleaf,需要引入一个头文件xmlns:th="http://www.thymeleaf.org",这样我们就可以用thymeleaf的语法了
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello thymeleaf
</body>
</html>
thymeleaf可以通过th:对所有的html元素进行操作,下面进行演示
获取后台数据,${}
package com.hzy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("test")
public String test(Model model) {
model.addAttribute("msg","<h1>hello</h1>");
return "test";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--不转义字符串-->
<div th:text="${msg}"></div>
<!--转义字符转-->
<div th:utext="${msg}"></div>
</body>
</html>
循环遍历后台数据
controller类
package com.hzy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
public class HelloController {
@RequestMapping("test")
public String test(Model model) {
List<String> list = new ArrayList<>();
list.add("abc");
list.add("def");
list.add("ghi");
model.addAttribute("list",list);
return "test";
}
}
test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:each="lis : ${list}" th:text="${lis}"></div>
</body>
</html>