1. thymeleaf运行之后就是纯HTML了,没运行之前也是纯HTML,这一点不同于JSP,jsp要解析成servlet等操作。
2. thymeleaf 不需要服务端的支持,前端人员可以直接的调试。
3. 页面标题要改为:
<html xmlns:th="http://www.thymeleaf.org">
4. application.properties配置文件
#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
spring.thymeleaf.cache=false
#上下文
server.context-path=/thymeleaf
5. maven要增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
6. 建立存放页面的文件夹。之前的jsp页面在webapp下的jsp下。
7. 然后就是一些例子,只有controller层和视图层。
controller:
@RequestMapping("/hello")
public String hello(Model m) {
m.addAttribute("name", "thymeleaf");
m.addAttribute("isTrue", false);
Date date =new Date();
m.addAttribute("now", date);
return "hello";
}
hello.html:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="../../webapp/js/thymeleaf.js"
th:src="@{/js/thymeleaf.js}"></script>
<script>
testFunction();
</script>
</head>
<body>
<p th:text="${name}"></p>
<p th:text="'Hello! ' + ${name} + '!'"></p>
<p th:text="|Hello! ${name}!|"></p>
<!-- 不只是布尔值的 true 和 false, th:if 表达式返回其他值时也会被认为是 true 或 false,规 则如下:
boolean 类型并且值是 true, 返回 true
数值类型并且值不是 0, 返回 true
字符类型(Char)并且值不是 0, 返回 true
String 类型并且值不是 "false", "off", "no", 返回 true
不是 boolean, 数值, 字符, String 的其他类型, 返回 true
值是 null, 返回 false -->
<p th:if="${isTrue}">true就显示出来</p>
<p th:if="${not isTrue}">不是true才显示出来</p>
<!-- 或者 -->
<p th:if="${isTrue}?'true就显示出来':'不是true才显示出来'"></p>
<div class="showing date">
<h2>格式化日期</h2>
直接输出日期 ${now}:
<p th:text="${now}"></p>
默认格式化 ${#dates.format(now)}:
<p th:text="${#dates.format(now)}"></p>
自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
<p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
</div>
</body>
</html>
遍历单选框table:
<tbody>
<tr th:each="p: ${page}">
<td th:text="${p.id}"></td>
<td th:text="${p.name}"></td>
<td><a th:href="@{/categories/{id}(id=${p.id})}">编辑</a></td>
<td><a class="delete" th:href="@{/categories/{id}(id=${p.id})}">删除</a></td>
</tr>
</tbody>
遍历填充单选框:
<div class="showing">
<h2>遍历 radio </h2>
<input name="product" type="radio" th:each="p:${page}" th:value="${p.id}" th:checked="${p.id==3}" th:text="${p.name}" />
</div>
遍历填充下拉框:
<select size="3">
<option th:each="p:${page}" th:value="${p.id}"
th:selected="${p.id==4}" th:text="${p.name}"></option>
</select>