建立工程前引入thymeleaf依赖
在templates中建html文件
在文件头加<html lang="en" xmlns:th="http://www.thymeleaf.org">
简单三步就可以使用thymeleaf了
1、展示基本元素
对象属性:<label th:text="${book.bookName}">图书名称(取不到值就会显示我)</label><br>
数字:<span th:text="${price}">价格</span><br>
字符串:<span th:text="${str}">很久以前</span><br>
对象:<span th:text="${book}">书本</span><br>
2、在style中使用
<style type="text/css" th:inline="css">
.style1{
color: [[${color}]];
}
</style>
书本名:<span class="style1" th:text="${book.bookName}">书本名:</span><br>
3、显示时不替换行内字符
<span th:inline="text">书本名:[[${book.bookName}]]</span>
4、显示对象
<div th:object="${book}">
<p th:text="*{bookId}"/>
<p th:text="*{bookName}"/>
<p th:text="*{bookAuthor}"/>
<p th:text="*{bookPrice}"/>
</div>
5、用each遍历
<table style="width: 600px;" border="1" cellspacing="0">
<caption>图书信息列表</caption>
<thead>
<tr>
<th>图书ID</th>
<th>图书名称</th>
<th>作者</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr th:each="b:${books}">
<td th:text="${b.bookId}"></td>
<td th:text="${b.bookName}"></td>
<td th:text="${b.bookAuthor}"></td>
<td th:text="${b.bookPrice}"/>
</tr>
</tbody>
</table>
6、用if判断
<table style="width: 600px;" border="1" cellspacing="0">
<caption>图书信息列表</caption>
<thead>
<tr>
<th>图书ID</th>
<th>图书名称</th>
<th>作者</th>
<th>价格</th>
<th>购买建议</th>
</tr>
</thead>
<tbody>
<tr th:each="b:${books}">
<td th:text="${b.bookId}"></td>
<td th:text="${b.bookName}"></td>
<td th:text="${b.bookAuthor}"></td>
<td th:text="${b.bookPrice}"/>
<td th:if="${b.bookPrice>40}" style="color: red;">太贵了!</td>
<th th:if="${b.bookPrice<=40}" style="color: darkgreen;">便宜!!</th>
</tr>
</tbody>
</table>
7、用switch判断
<table style="width: 600px;" border="1" cellspacing="0">
<caption>图书信息列表</caption>
<thead>
<tr>
<th>图书ID</th>
<th>图书名称</th>
<th>作者</th>
<th>价格</th>
<th>购买建议switch</th>
</tr>
</thead>
<tbody>
<tr th:each="b:${books}">
<td th:text="${b.bookId}"></td>
<td th:text="${b.bookName}"></td>
<td th:text="${b.bookAuthor}"></td>
<td th:text="${b.bookPrice}"/>
<td th:switch="${b.bookPrice/10}">
<label th:case="3">价格便宜</label>
<label th:case="4">价格合理</label>
<label th:case="5">价格太贵</label>
<label th:case="6">价格太贵</label>
</td>
</tr>
</tbody>
</table>
8、碎片使用
a当主页面,footer和header当碎片
所有页面都要加 <html lang="en" xmlns:th="http://www.thymeleaf.org">
header
<div th:fragment="fragment1" style="width: 100%;height: 80px;background: deepskyblue; color: white; font-size: 25px;">
#############header##############
</div>
footer
<div th:fragment="fragment2" style="width: 100%;height: 30px;background: lightblue; color: white; font-size: 16px;">
#############footer###########
</div>
a (使用include,不会引入style)
<div th:include="header::fragment1"></div>
<div style="width: 100%; height: 500px;">
定义内容
</div>
<div th:include="footer::fragment2"></div>
a (使用replace,会引入style)
<div th:replace="header::fragment1"></div>
<div style="width: 100%; height: 500px;">
定义内容
</div>
<div th:replace="footer::fragment2"></div>
总结:注意在文件头加xmlns,会用th:text th:each th:if th:switch th:replace,基本就够了