前面介紹了Spring Boot的優點,然后介紹了如何快速創建Spring Boot 項目。不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html。
今天我們主要來看看 Thymeleaf 在 Spring Boot 中的整合!
這個系列課程的完整源碼,也會提供給大家。大家關注我的微信公眾號(架構師精進),回復:springboot源碼 獲取這個系列課程的完整源碼。或者點此鏈接直接下載完整源碼
Thymeleaf 簡介
Spring Boot 2主要支持頁面模板是 Thymeleaf 和 Freemarker ,當然,作為 Java 最最基本的頁面模板 Jsp ,Spring Boot 也是支持的,只是使用比較麻煩。
Thymeleaf 作為新一代 Java 模板引擎,它的功能與 Velocity、FreeMarker 等傳統 Java 模板引擎比較類似,但是Thymeleaf 模板后綴為 .html
,可以直接被瀏覽器打開,因此,開發時非常方便。
它既可以讓前端工程師在瀏覽器中直接打開查看樣式,也可以讓后端工程師結合真實數據查看顯示效果,同時,SpringBoot 提供了 Thymeleaf 自動化配置解決方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。
事實上, Thymeleaf 除了展示基本的 HTML ,進行頁面渲染之外,也可以作為一個 HTML 片段進行渲染,例如我們在做郵件發送時,可以使用 Thymeleaf 作為郵件發送模板。
整合
新項目整合 Thymeleaf 非常容易,只需要創建項目時勾上 Thymeleaf 即可,這里就不說了。
下面說說怎么在現有的項目中手動整合Thymeleaf:
1、在pom.xml 增加依賴如下:
<!-- 引入 thymeleaf 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-thymeleaf</artifactId> </dependency>
2、application.properties 文件增加Thymeleaf 相關配置
############################################################ # # thymeleaf 模板 # ############################################################ spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type=text/html # 關閉緩存 spring.thymeleaf.cache=false
spring.thymeleaf.prefix 指定模板頁面的路徑
3、增加前台頁面
在resource\templates\thymeleaf 目錄下增加index.html 頁面
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello Spring Boot~~~~~~~</h1>
</body>
</html>
th:text 就是Thymeleaf的標簽,
用於處理標簽體的文本內容。
其他更對的標簽及用法,我會在下一篇文章中介紹。
注意:實際開發項目直接放resource\templates目錄下就行,不需要加Thymeleaf 目錄。我這里是有驗證其他模板引擎框架,所以做了個目錄區分。
4、創建 Controller
接下來我們就可以創建 Controller 了,實際上引入 Thymeleaf 依賴之后,我們可以不做任何配置。新建的ThymeleafController如下:
package com.weiz.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.weiz.pojo.User; @Controller @RequestMapping("th") public class ThymeleafController { @RequestMapping("/index") public String index(ModelMap map) { map.addAttribute("name", "thymeleaf-index"); return "thymeleaf/index"; }
}
在ThymeleafController
中返回邏輯視圖名,邏輯視圖名為 index
,意思我們需要在 resources/templates/t
目錄下提供一個名為 hymeleaf
index.html
的 Thymeleaf
模板文件。
注意:實際開發項目直接放resource\templates目錄下就行,不需要加Thymeleaf 目錄。我這里是有驗證其他模板引擎框架,所以做了個目錄區分。
5、運行效果
在瀏覽器中輸入:http://localhost:8080/th/index 查看頁面返回結果。
總結
主要向大家簡單介紹了 Spring Boot 整合 Thymeleaf,還是比較簡單的。下一篇文章會給大家詳細介紹Thymeleaf的常用標簽和用法。大家也可以閱讀 Thymeleaf 官方文檔學習 Thymeleaf 的更多用法。
這個系列課程的完整源碼,也會提供給大家。大家關注我的微信公眾號(架構師精進),回復:springboot源碼 獲取這個系列課程的完整源碼。