1. 程式人生 > 其它 >Spring boot 整合 thymeleaf

Spring boot 整合 thymeleaf

技術標籤:Spring bootspringjava前端

Spring boot 整合 thymeleaf

thymeleaf 的作用

Thymeleaf 是一個模板引擎,完全可以替換JSP

Thymeleaf 特點

  • Thymeleaf在有網路和無網路的環境下皆可執行,即它可以讓美工在瀏覽器檢視頁面的靜態效果,也可以讓程式設計師在伺服器檢視帶資料的動態頁面效果。
  • Thymeleaf開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、OGNL表示式效果,避免每天套模板、改jstl、改標籤的困擾。同時開發人員也可以擴充套件和建立自定義的方言。
  • Thymeleaf提供spring標準方言和一個與SpringMVC完美整合的可選模組,可以快速的實現表單繫結、屬性編輯器、國際化等功能。

Spring boot 整合 thymeleaf

1,依賴配置

  • 自動配置,使用IntelliJ 建立Springboot專案時,Spring初始化時,在模板引擎中選中Thymeleaf即可。
  • 手動配置,在pom.xml依賴配置檔案中加入
<dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2,在application.properties(application.yml)屬性配置檔案中配置thymeleaf(自動配置不需要)

# thymeleaf 配置
spring.thymeleaf.prefix=classpath:/templates/ 
spring.thymeleaf.check-template-location=true 
spring.thymeleaf.suffix=.html 
spring.thymeleaf.encoding=UTF-8 
spring.thymeleaf.content-type=text/html 
spring.thymeleaf.mode=HTML5 
spring.thymeleaf.cache=false

3,定義和使用模板,一般,我們將head,header,aside,footer等公用的網頁部分定義為模板

  • 定義模板(在html標籤中加入xmlns:th=“http://www.thymeleaf.org”)
<footer th:fragment="copy">
    HelloWorld!
</footer>
  • 使用模板
    • insert
    //匯入片段
    <div th:insert="footer::copy"></div>
    //結果
    <div>
        <footer>
            HelloWorld!
        </footer>
    </div>
    
    • replace
    /匯入片段
    <div th:replace="footer::copy"></div>
    //結果
    <footer>
        HelloWorld!
    </footer>
    
    • include
    /匯入片段
    <div th:include="footer::copy"></div>
    //結果
    <div>
        HelloWorld!
    </div>
    

4,使用thymeleaf從model獲取資料(在controller中用Model.addAttribute(“name”,name)獲取資料),${}

  • <head th:replace="common/template_head::head('Animal:'+${animal.name})">
  • <td th:text="${user.loginName}"></td>
    //each迴圈從productList中獲取product
    <tr th:each="product : ${productList}">
                <td>
                    <a href="#" th:text="${product.productId}">FL-DLH-02</a>
                </td>
                <td th:text="${product.name}">Persian</td>
    </tr>

5,常用表示式

  • ${...}變量表達式。
  • * { .. . } 選擇表示式。
  • #{...}訊息文字表達式。
  • @ {} 連結url 表示式。
  • #maps 工具物件表示式。
    6,常用標籤
  • th:action 定義後臺控制器路徑。
  • th:each 1,盾環語-句。
  • th:field 表單欄位繫結。
  • th:href 定義超連結。
  • th:id div 標籤中的ID 宣告,類似HTML 標籤中的歸屬性。
  • th:if 條件判斷語句。
  • th:include 佈局標籤,替換內容到引入檔案。
  • th :企agment 佈局標籤,定義一個程式碼片段,方便其他地方引用。
  • th:object 替換物件。
  • th:src 圖片類地址引入。
  • th:text 顯示文字。
  • th:value 屬性賦值。
    7,常用函式
  • #dates 日期函式。
  • #lists 列表函式。
  • #arrays 陣列函式。
  • #strings 字串函式。
  • #numbers 幸生字函捷生。
  • #ca lendars 日曆函式。
  • #objects 物件函式。
  • #bools 邏輯函式。

rays 陣列函式。

  • #strings 字串函式。
  • #numbers 幸生字函捷生。
  • #ca lendars 日曆函式。
  • #objects 物件函式。
  • #bools 邏輯函式。