Thymeleaf ?
- Thymeleaf
是一个现代的服务器端Java模板引擎的web和独立的环境。
Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板- HTML,可以正确地显示在浏览器,也可以作为静态原型,允许在开发团队更强大的协作。
有了Spring框架的模块,与您喜欢的工具的大量集成,以及插入您自己的功能的能力,Thymeleaf是现代HTML5 JVM web开发的理想选择——尽管它可以做的还有很多
(翻译自官网) - 简单来说
模板引擎(例如jsp)
数据渲染
Spring推荐
单一应用,不适合前后端分离
配置依赖
<!-- Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
页面跳转
-
一般将Thymeleaf(html作为其视图载体)文件放在maven项目的template目录下,
而该目录下不能直接被访问,因此需要写一个
页面跳转Controller
/** * 页面跳转Controller */ @Controller public class PageController { /** * 页面跳转方法 */ @GetMapping("/show") public String showPage(Model model){ model.addAttribute("msg","Hello, Thymeleaf!"); return "index";//跳转到index.html } }
-
通用的页面跳转
/**
* 页面跳转Controller
*/
@Controller
public class PageController {
/**
* 页面跳转方法
*/
@RequestMapping("/{page}")
public String showPage(@PathVariable String page){
return page;
}
}
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns:th="http://www.thymeleaf.org"><!-- thymeleaf命名空间定义 --> <head> <title>Hello,Thymeleaf!</title> </head> <body> <span th:text="CodePandas"></span> <hr/> <span th:text="${msg}"></span> </body> </html>
语法
字符串与变量输出
th:text
-
th:text=""输出字符串
<span th:text="CodePandas">test</span>
-
输出变量
<span th:text="${msg}"></span>
th:value
<input th:value="${msg}">
可以将一个值放入到input标签的value中,可以做数据回填
迭代遍历
th:each 迭代 List
(set同)
<tr th:each="u : ${list}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
<td th:text="${u.age}"></td>
</tr>
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org"><!-- thymeleaf命名空间定义 -->
<head>
<title>Hello,Thymeleaf!</title>
</head>
<body>
<span th:text="CodePandas">test</span>
<hr/>
<table border="1" width="50%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="u : ${list}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
<td th:text="${u.age}"></td>
</tr>
</table>
</body>
</html>
th:each 迭代 Map
<table border="1" width="50%">
<tr>
<th>UserNo</th>
<th>UserId</th>
</tr>
<tr th:each="m : ${map}">
<td th:text="${m.key}"></td>
<td th:text="${m.value.id}"></td>
</tr>
</table>
URL 表达式
- 绝对路径
<a th:href="@{https://blog.csdn.net/weixin_43488958/article/details/105420935}">SpringBoot整合JDBC</a>
- 相对路径
<a th:href="@{/show2}">打开index2</a>
- 对应的跳转Controller
@GetMapping("/show2")
public String show2(){
return "index2";
}
- URL传参
- 普通方式
<a th:href="@{/show2?id=1&name=admin}">普通url传参</a>
- Restful风格
<a th:href="@{/show2/{id}/{name}(id=1,name=zgs)}">Restful url传参</a>
@GetMapping("/show2/{id}/{name}")
public String show2(@PathVariable String id, @PathVariable String name){
System.out.println(id+"\t"+name);
return "index2";
}