添加Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
自动给我们默认分配了模版的前缀和后缀,我们只需要按部就班的将模版丢进去即可
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
private Charset encoding;
private boolean cache;
Spring Boot默认存放模板页面的路径在src/main/resources/templates
数据显示
通过Controller将数据传递到页面中
显示普通文本
创建一个Controller对象,在其中进行参数的传递
@Controller
public class ThymeleafController {
@RequestMapping(value = "show", method = RequestMethod.GET)
public String show(Model model){
model.addAttribute("uid","123456789");
model.addAttribute("name","Jerry");
return "show";
}
}
在SpringBoot默认的页面路径下创建show.html文件,内容如下
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot模版渲染</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<p th:text="'用户ID:' + ${uid}"/>
<p th:text="'用户名称:' + ${name}"/>
</body>
</html>
可以看到在p标签中有th:text属性,这个就是thymeleaf的语法,它表示显示一个普通的文本信息。
提取公共页面
<div th:fragment="sidebar"> </div>
<div th:replace="~{commons::sidebar}"> </div>
//如果要传参可以直接用(),接收判断即可
//model.addAttribute("emps",emps)
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.getId}"></td>
<td th:text="${emp.getName}"></td>
<td>[[${emp.getEmail}]]</td>//两种取值方法
<td th:text="${#dates.format(emp.getBirth(),‘yyyy-MM-dd HH:mm:ss’)}"></td>//格式化
</tr>
</tbody>
//bootstrap下拉框,model.setAttribute("departments",departments)
<div class="form-group">
<label></label>
<select class="form-control" name="department">
<option th:each="dept:${departments}" th:text="${dept}"></option>
</select>
</div>
增删改查
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.getId}"></td>
<td th:text="${emp.getName}"></td>
<td>[[${emp.getEmail}]]</td>
<td th:text="${#dates.format(emp.getBirth(),‘yyyy-MM-dd HH:mm:ss’)}"></td>
<td>
//th:href="@{/emp/}+${emp.getId()}" 给emp传值
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">编辑</a>
</td>
</tr>
</tbody>
https://www.jianshu.com/p/a842e5b5012e
https://www.cnblogs.com/jiangbei/p/8462294.html