SpringBoot2.x整合Thymeleaf

一、Thymeleaf簡介

Thymeleaf是一個流行的模板引擎,該模板引擎採用Java語言開發,除了thymeleaf之外還有Velocity、FreeMarker等模板引擎,功能類似。Thymeleaf是用來開發Web和獨立環境項目的服務器端的Java模版引擎;Spring官方支持的服務的渲染模板中,並不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf與SpringMVC的視圖技術,及SpringBoot的自動化配置集成非常完美,幾乎沒有任何成本,你只用關注Thymeleaf的語法即可。

Thymeleaf的特點

  • 動靜結合:Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。

  • 開箱即用:它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言。

  • 多方言支持:Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。

  • 與SpringBoot完美整合,SpringBoot提供了Thymeleaf的默認配置,並且爲Thymeleaf設置了視圖解析器,我們可以像以前操作jsp一樣來操作Thymeleaf。代碼幾乎沒有任何區別,就是在模板語法上有區別。

 

二、在SpringBoot中集成Thymeleaf

1、添加依賴

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
       <!-- thymeleaf會對html中的標籤進行嚴格校驗,如果html標籤缺少結束標籤的話,thymeleaf會報錯,我們可以通過下面方式去除thymeleaf的校驗 -->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>

 

2、properties配置

application.properties文件內容如下:

server.port=8080
spring.application.name=springboot-thymeleaf
#開發時建議關閉Thymeleaf緩存
spring.thymeleaf.cache=false

 

3、編寫測試Controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping
public class ThymeleafController {

    @RequestMapping("index")
    public String index(Model model){
        model.addAttribute("msg", "Hello Thymeleaf");
        return "index";
    }
}

 

4、編寫測試Thymeleaf模板文件

在resources下新建 templates文件夾,在templates文件夾下新建html5文件index.html

index.html文件內容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>springboot2.x整合Thymeleaf</title>
</head>
<body>
<h1 th:text="${msg}">來看下效果</h1>
<!-- 非H5頁面可以使用如下指令 -->
<h1 data-th-text="${msg}">來看下效果</h1>
</body>
</html>

SpringBoot使用Thymeleaf作爲視圖,模板文件放置在resources/templates目錄下,靜態資源放置在resources/static目錄下,這是默認配置,會自動生效。

從自動裝配的代碼中可以看出:

 

 

5、編寫SpringBoot啓動類

@SpringBootApplication
public class ThymeleafApplication {

    public static void main(String[] args) {
        SpringApplication.run(ThymeleafApplication.class, args);
    }
}

運行該程序,瀏覽器訪問:http://127.0.0.1:8080/index

 

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