Spring Boot官方推荐使用的模板引擎是Thymaleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframeWork.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
# 是否开启缓存,开发时可以设置为false,默认为true
spring.thymeleaf.cache=true
# 检查模板是否存在,默认为true
spring.thymeleaf.check-template=true
# 检查模板位置是否存在 默认为true
spring.thymeleaf.check-template-location=true
# 模板文件编码
spring.thymeleaf.encoding=UTF-8
# 模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
# content-type配置
spring.thymeleaf.servlet.content-type=text/html
# 模板文件后缀
spring.thymeleaf.suffix=.html
@GetMapping("/findAll")
public String findAll(Model model){
List<Emp> emps = empService.findAll();
model.addAttribute("emps",emps);
return "/ems/emplist";
}
- classpath:/templates/ems/emplist.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">
<head>
<title>emplist</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" th:href="@{/css/style.css}" />
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
2009/11/20
<br />
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">main</a>
</h1>
</div>
<div id="navigation">
</div>
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
Welcome!
</h1>
<table class="table">
<tr class="table_header">
<td>
ID
</td>
<td>
Name
</td>
<td>
Salary
</td>
<td>
Age
</td>
<td>
Bir
</td>
<td>
Operation
</td>
</tr>
<tr class="row1" th:each = "emp:${emps}">
<td>
<span th:text="${emp.id}"></span>
</td>
<td>
<span th:text="${emp.name}"></span>
</td>
<td>
<span th:text="${emp.salary}"></span>
</td>
<td>
<span th:text="${emp.age}"></span>
</td>
<td>
<span th:text="${#dates.format(emp.bir,'yyyy-MM-dd')}"></span>
</td>
<td>
<a th:href="@{/emp/delete(id=${emp.id})}">delete emp</a> <a th:href="@{/emp/find(id=${emp.id})}">update emp</a>
</td>
</tr>
</table>
<p>
<input type="button" class="button" value="Add Employee" onclick="location.href='/ems/toSave'"/>
</p>
</div>
</div>
<div id="footer">
<div id="footer_bg">
ABC@126.com
</div>
</div>
</div>
</body>
</html>
Thymeleaf的一些用法笔记
<html xmlns:th="http://www.thymeleaf.org">
</html>
- 设置文本内容的值 th:text
- 设置input的值 th:value
- 循环输出 th:each
- 变量表达式 ${…}
- 链接表达式 @{…}
- 无参: @{/xxx}
- 有参: @{/xxx(k1=v1,k2=v2)} 对应url结构 xxx?k1=v1&k2=v2
推荐一篇关于Thymeleaf深度好文,自己也当作收藏可以翻阅