SpringBoot 爲我們提供了 Thymeleaf 自動化配置解決方案,所以我們在 SpringBoot 中使用 Thymeleaf 非常方便
一、簡介
Thymeleaf是一個流行的模板引擎,該模板引擎採用Java語言開發,模板引擎是一個技術名詞,是跨領域跨平臺的概念,在Java語言體系下有模板引擎,在C#、PHP語言體系下也有模板引擎。除了thymeleaf之外還有Velocity、FreeMarker等模板引擎,功能類似。
Thymeleaf的主要目標在於提供一種可被瀏覽器正確顯示的、格式良好的模板創建方式,因此也可以用作靜態建模。你可以使用它創建經過驗證的XML與HTML模板。使用thymeleaf創建的html模板可以在瀏覽器裏面直接打開(展示靜態數據),這有利於前後端分離。需要注意的是thymeleaf不是spring旗下的。
二、整合
- 1、引入 thymeleaf,在 pom.xml 文件中加入:
<!-- thymeleaf 模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- web 開發 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
由於 SpringBoot 爲 thymeleaf 提供了一整套的自動化配置方案,使得我們幾乎不需要做任何更改就可以直接使用了
- 2、SpringBoot 中 thymeleaf 默認配置
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
/**
* Whether to check that the template exists before rendering it.
*/
private boolean checkTemplate = true;
/**
* Whether to check that the templates location exists.
*/
private boolean checkTemplateLocation = true;
/**
* Prefix that gets prepended to view names when building a URL.
*/
private String prefix = DEFAULT_PREFIX;
/**
* Suffix that gets appended to view names when building a URL.
*/
private String suffix = DEFAULT_SUFFIX;
/**
* Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
*/
private String mode = "HTML";
...
}
通過 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 找到 SpringBoot 中 thymeleaf 的默認配置,我們不難看出
默認編碼格式:UTF-8
默認路徑:classpath:/templates/,都放在根目錄下的 templates 目錄下
默認後綴:.html,thymeleaf 都是 html 文件
檢查模板:默認開啓
檢查模板位置:默認開啓
…
從上述源碼可以看出,我們的 thymeleaf 模板文件默認放在 resources/templates 目錄下,默認的後綴是 .html
當然,我們不想使用默認配置,我們也可以在 application.tml 文件中以 spring.thymeleaf 開始個性配置
例如:
spring:
# thymeleaf模板引擎配置
thymeleaf:
# 緩存
cache: false
# 編碼格式
encoding: UTF-8
我們在開發中,可能被緩存坑過很多次,我們可以將 thymeleaf 中的緩存給關閉,保持實時更新
三、開發
- 1、創建控制層 IndexController.java
@Controller
public class IndexController {
/**
* 請求 index 頁面
* @return
*/
@GetMapping("index")
public ModelAndView index() {
ModelAndView mav = new ModelAndView("index");
mav.addObject("title", "首頁");
List<UserInfo> list = new ArrayList<>();
UserInfo user = null;
for (int i = 0; i < 10; i++) {
user = new UserInfo();
user.setId(i + 1);
user.setNickName("user" + i);
user.setSignature("SpringBoot真香,+" + (i + 1));
list.add(user);
}
mav.addObject("users", list);
return mav;
}
}
我們創建了 IndexController,請求 index 返回 index.html 頁面,
- 2、創建 thymeleaf 模板 index.html
下面我們在 resources/templates 目錄下創建 index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}"></title>
</head>
<body>
<table border="1">
<tr>
<td>用戶編號</td>
<td>用戶暱稱</td>
<td>個性簽名</td>
</tr>
<tr th:each="item : ${list}">
<td th:text="${item.id}"></td>
<td th:text="${item.nickName}"></td>
<td th:text="${item.signature}"></td>
</tr>
</table>
</body>
</html>
注意:
xmlns=“http://www.w3.org/1999/xhtml” xmlns:th=“http://www.thymeleaf.org”,是必須要在 html 標籤中寫入的
xmlns 是xml namespace的縮寫,也就是 XML 命名空間
xmlns 屬性可以在文檔中定義一個或多個可供選擇的命名空間
該屬性可以放置在文檔內任何元素的開始標籤中
該屬性的值類似於URL,它定義了一個命名空間,瀏覽器會將此命名空間用於該屬性所在元素內的所有內容
我們在 ModelAndView 中傳入了 title 參數,使用 th:text="${title}" 給 title 標籤賦值,與 JSTL 使用方式類似,效果如圖:
我們還通過 th:each=“item : ${list}” 渲染了一個用戶表格,如圖:
- 3、拼接 URL
<a th:href="@{/user/info(id=${user.id})}">參數拼接</a>
<a th:href="@{/user/info(id=${user.id},phone=${user.phone})}">多參數拼接</a>
<a th:href="@{/user/info/{uid}(uid=${user.id})}">RESTful風格</a>
<a th:href="@{/user/info/{uid}/abc(uid=${user.id})}">RESTful風格</a>
四、thymeleaf 在 JavaScript 中的使用技巧
- 1、開發前戲
<script type="text/javascript" th:inline="javascript">
...
</script>
我們需要在 script 標籤中寫入 th:inline=“javascript”,註明使用 thymeleaf 的內聯方法
- 2、Ajax 路徑問題
url: /*[[@{/user/saveUser}]]*/,
data: {
'user': user
}
type: 'post',
dataType: 'json',
我們使用 /[[@{/**}]]/ 來獲取項目的上下文路徑,訪問項目
- 3、獲取 model 中的數據
<script type="text/javascript" th:inline="javascript">
var userName = [[${user.name}]];
</script>
4、使用前端框架的 iframe 彈窗,例如 layui
function showUserInfo() {
layer.open({
type: 2,
title: '用戶信息',
shade: 0.2,
area: ['600px', '450px'],
offset: '100px',
shadeClose: false,
content: /*[[@{/user/getUserInfo}]]*/
});
}
需要傳參:
layer.open({
type: 2,
title: '用戶信息',
shade: 0.2,
area: ['600px', '450px'],
offset: '100px',
shadeClose: false,
content: [[@{/user/getUserInfo}]]+'?id='+id
});
我們在路徑中傳入了用戶的 id
五、手動渲染
我們在發送郵件的時候,會需要使用到郵件模板,我們選擇手動渲染即可
- 1、新建一個郵件模板 email.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>歡迎加入我們</title>
</head>
<body>
<h1 style="text-align: center">入職歡迎</h1>
<p><span th:text="${user.name}"></span>:你好!!!歡迎加我們XXX公司,你的入職信息如下:</p>
<p>崗位:<span th:text="${user.job}"></span></p>
<p>月薪:<span th:text="${user.wages}"></span></p>
</body>
</html>
- 2、發送郵件測試
@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
Context context = new Context();
context.setVariable("name", "張三");
context.setVariable("job", "Java開發工程師");
context.setVariable("wages", 7800);
String mail = templateEngine.process("email", context);
emailUtils.sendHtmlMail("[email protected]", "入職通知", mail);
}
SpringBoot 中發送郵件的教程請看:SpringBoot中發送郵件
- 3、效果展示
最終,我們收到如下郵件:
總結:
Spring Boot 針對 Thymeleaf 提供了一整套的自動化配置方案,這對我們在 SpringBoot 中使用 Thymeleaf 更加方便,SpringBoot 爲我們提供了默認配置,我們也可以對其進行個性化配置
以上就是我們在學習 SpringBoot 整合 Thymeleaf 時的一些知識點,更多內容請訪問:Thymeleaf 官方文檔
Thymeleaf 的官方文檔:https://www.thymeleaf.org
如您在閱讀中發現不足,歡迎留言!!!