SpringBoot 集成Thymeleaf

Thymeleaf 簡介

什麼是 Thymeleaf

Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。相較與其他的模板引擎,它有如下三個極吸引人的特點

  • Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板 + 數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
  • Thymeleaf 開箱即用的特性。它提供標準和 Spring 標準兩種方言,可以直接套用模板實現 JSTL、 OGNL 表達式效果,避免每天套模板、改 JSTL、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言。
  • Thymeleaf 提供 Spring 標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。

爲什麼需要 Thymeleaf

如果希望以 Jar 形式發佈模塊則儘量不要使用 JSP 相關知識,這是因爲 JSP 在內嵌的 Servlet 容器上運行有一些問題 (內嵌 Tomcat、 Jetty 不支持 Jar 形式運行 JSP,Undertow 不支持 JSP)。

Spring Boot 中推薦使用 Thymeleaf 作爲模板引擎,因爲 Thymeleaf 提供了完美的 Spring MVC 支持,Spring Boot 提供了大量模板引擎,包括:

  • FreeMarker
  • Groovy
  • Mustache
  • Thymeleaf
  • Velocity
  • Beetl

示例

引入依賴

<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>
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

主要增加 spring-boot-starter-thymeleafnekohtml 這兩個依賴

  • spring-boot-starter-thymeleaf:Thymeleaf 自動配置
  • nekohtml:允許使用非嚴格的 HTML 語法

配置 Thymeleaf

application.yml 配置 Thymeleaf

spring:
    freemarker:
        enabled: true #是否啓用thymeleaf作爲視圖解析
        cache: false # 緩存配置 開發階段應該配置爲false 因爲經常會改
        charset: UTF-8 # 文件編碼
        #前綴,也就是模板存放的路徑
        prefix: classpath:/templates/
        suffix: .html # 模版後綴名 默認爲ftl
        #編碼格式
        encoding: UTF-8
        #設置不嚴格的html
        mode: HTML
        servlet:
            content-type: text/html

創建測試用實體類

/**
 * 部門
 * @author HC
 */
public class Dept {
	/**
	 * 部門編號
	 */
    private Integer deptno;
    /**
     * 部門名稱
     */
    private String dname;
    /**
     * 部門地址
     */
    private String loc;

    public Dept() {
    }

    public Dept(Integer deptno, String dname, String loc) {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptno=" + deptno +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }
}

創建測試用 Controller

創建一個 Controller,造一些測試數據並設置跳轉

@Controller
@RequestMapping(value = "thymeleaf")
public class IndexController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        List<Dept> depts = new ArrayList<>();
        depts.add(new Dept(10,"ACCOUNTING","NEWYORK"));
        depts.add(new Dept(20,"RESEARCH","DALLAS"));
        depts.add(new Dept(30,"SALES","CHICAGO"));
        depts.add(new Dept(40,"OPERATIONS","BOSTON"));
        model.addAttribute("depts", depts);
        return "index";
    }
}

創建測試頁面

templates 目錄下創建 index.html 文件,代碼如下:

<!-- 修改 html 標籤用於引入 thymeleaf 引擎,這樣纔可以在其他標籤裏使用 `th:*` 語法  -->
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
    <div>
        <span>訪問 Model:</span><span th:text="${person.name}"></span>
    </div>
    <div>
        <span>訪問列表</span>
        <table>
            <thead>
                <tr>
                    <th>部門編號</th>
                    <th>部門名稱</th>
                    <th>部門地址</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="dept : ${depts}">
                    <td th:text="${dept.deptno}"></td>
                    <td th:text="${dept.dname}"></td>
                    <td th:text="${dept.loc}"></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

測試訪問

啓動成功後,訪問:http://localhost:8080/thymeleaf/index 即可看到效果

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