玩轉 SpringBoot 2 快速整合 | Thymeleaf 篇

前言

Thymeleaf是一個適用於Web和獨立環境的現代服務器端Java模板引擎。

Thymeleaf的主要目標是爲您的開發工作流程帶來優雅的自然模板 - 可以在瀏覽器中正確顯示的HTML,也可以用作靜態原型,從而在開發團隊中實現更強大的協作。

通過Spring Framework模塊,與您喜歡的工具的大量集成,以及插入您自己的功能的能力,Thymeleaf是現代HTML5 JVM Web開發的理想選擇 - 儘管它可以做得更多。
——摘抄自Thymeleaf官網介紹 鏈接:https://www.thymeleaf.org/ind...

Thymeleaf與Velocity或FreeMarker等其他模板引擎相比如何?

Velocity 和 FreeMarker 都是非常棒的軟件,但是它們處理模板問題的原理與Thymeleaf 完全不同。

Thymeleaf 非常強調自然模板化——允許模板成爲工作原型,而其他兩個模板不允許這樣做——它的語法試圖(可以說)更乾淨,更符合當前 web開發的趨勢。另外,從架構的角度來看,Velocity 和 FreeMarker 都是順序文本處理器,而 Thymeleaf 是基於標記解析技術的。這允許 Thymeleaf 利用特定於基於標記的環境的有趣特性,特別是web。

無論如何,比較這些技術的最好方法是自己使用它們,並感覺哪個最適合你。

以上內容來自Thymeleaf官網 鏈接: https://www.thymeleaf.org/faq...

SpringBoot使用Thymeleaf 操作步驟

第一步是引入Thymeleaf starter依賴,具體代碼如下:

        <!-- thymeleaf 相關依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

第二步是在 application.properties 添加 Thymeleaf 相關配置,具體配置如下:

server.port=8090
server.servlet.context-path=/sbe

#關閉 Thymeleaf 的緩存開發過程中無需重啓
spring.thymeleaf.cache = false
#設置thymeleaf頁面的編碼
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#設置thymeleaf頁面的後綴
spring.thymeleaf.suffix=.html
#設置thymeleaf頁面的存儲路徑
spring.thymeleaf.prefix=classpath:/templates/

第三步是編寫訪問 Thymeleaf 頁面 Controller。

@Controller
@RequestMapping("/hello")
public class ThymeleafHelloWrodController {
    
    @RequestMapping("/thymeleaf")
    public String helloThymeleaf(Model model){
        model.addAttribute("hello","hello Thymeleaf!");
        return "hello/index";
    }
}

Thymeleaf 頁面代碼如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <p th:text="${hello}">hello</p>
</body>
</html>

測試

在遊覽器輸入訪問 Thymeleaf 頁面的 Controller 的 URL:http://localhost:8090/sbe/hello/thymeleaf 進行測試,測試結果如下:
在這裏插入圖片描述

小結

SpringBoot 使用 Thymeleaf 步驟如下:

  1. 引入Thymeleaf starter依賴
  2. 添加 Thymeleaf 相關配置
  3. 編寫訪問 Thymeleaf 頁面和 Controller

代碼示例

具體代碼示例請查看我的GitHub 倉庫 springbootexamples 中的 spring-boot-2.x-thymeleaf 下的 helloword 包下查看。

GitHub:https://github.com/zhuoqianmi...

如果您對這些感興趣,歡迎 star、或點贊給予支持!轉發請標明出處!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章