Thymeleaf模板
Thymeleaf的優點:它就是html頁面
相關pom依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
注意:
Spring Boot官方文檔建議在開發時將緩存關閉,那就在application.properties文件中加入下面這行
spring.thymeleaf.cache=false
正式環境還是要將緩存開啓的
application.properties–》application.yml
1、application.yml文件的默認配置
spring:
thymeleaf:
cache: false
在controller中跳轉:
thymeleaf標籤:
在頁面上方導入<html xmlns:th="http://www.thymeleaf.org">
(1)取值
<h1 th:text="${name}" >xxx</h1>
(2)foreach
<table border="1px" >
<thead>
<tr>
<td>用戶id</td>
<td>用戶姓名</td>
<td>用戶描述</td>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.uid}" >用戶id</td>
<td th:text="${user.username}">用戶姓名</td>
<td th:text="${user.desc}">用戶描述</td>
</tr>
</tbody>
</table>
(3)下拉框
<select>
<option th:each="user : ${users}" th:value="${user.uid}" th:text="${user.username}" ></option>
</select>
Freemarker模板
相關pom依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.yml文件的默認配置:
spring:
freemarker:
# 設置模板後綴名
suffix: .ftl
# 設置文檔類型
content-type: text/html
# 設置頁面編碼格式
charset: UTF-8
# 設置頁面緩存
cache: false
# 設置ftl文件路徑,默認是/templates,爲演示效果添加role
template-loader-path: classpath:/templates/role
mvc:
static-path-pattern: /static/**
怎麼添加創建ftl文件:
要添加後纔會有
在controller中跳轉:
注意:
freemarker標籤:
(1)取值
xxxxxxx 【${name!"我靠"}】
注意:如果後臺傳的值是null,不加!會報錯,!後面的值表示默認值
(2)非空判斷
exists用在邏輯判斷
<#if name??>
xxxx
</#if>
<#if name?exists>
${name}
</#if>
(3)條件表達式
<#if sex=="boy">
男
<#elseif sex=="girl">
女
<#else>
人妖
</#if>
(4)循環
<table border="1px" >
<thead>
<tr>
<td>用戶id</td>
<td>用戶姓名</td>
<td>用戶描述</td>
</tr>
</thead>
<tbody>
<#list users as user>
<tr >
<td >${user.uid}</td>
<td >${user.username}</td>
<td >${user.desc}</td>
</tr>
</#list>
</tbody>
</table>
注意:freemarker和thymeleaf的數據源位置不同
(5)獲取項目名(局部變量、全局變量)
<h1>獲取項目名(局部變量、全局變量)</h1>
局部變量
<#assign ctx1>
${springMacroRequestContext.contextPath}
</#assign>
全局變量
<#global ctx2>
${springMacroRequestContext.contextPath}
</#global>
${ctx1},${ctx2}
(6)調用外部文件
<#include "foot.ftl">