1. 程式人生 > >Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 頁面

Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 頁面

Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 頁面

在《Spring Boot(一):快速開始》中介紹瞭如何使用 Spring Boot 構建一個工程,並且提供 RESTful API ,本節我們繼續介紹如何使用 Spring Boot 渲染 Web 頁面。

1. 什麼是 Thymeleaf ?

雖然我們目前擁有許多十分優秀的前端框架,例如: Vue 、 React 等,非常適用於前後端分離的場景,前端可以獨立部署成為服務,前後端從物理上完全進行隔離,降低程式耦合度。但是 Spring Boot 官方依然為我們提供了模版引擎用於一些無需前後端分離的場景。 Thymeleaf 是新一代的模板引擎,在 Spring Boot 中,官方推薦使用 Thymeleaf 來做前端模版引擎。開啟 https://start.spring.io/ 可以看到,在當前Spring Boot 的版本中( 2.1.8.RELEASE ), 官方提供的模版引擎有以下幾種:

  • Thymeleaf
  • FreeMarker
  • Mustache
  • Groovy

Spring Boot 建議使用這些模版引擎,而並不推薦我們繼續使用 JSP 。

Thymeleaf 具體特性如下:

  • Thymeleaf 在有網路和無網路的環境下皆可執行,即它可以讓美工在瀏覽器檢視頁面的靜態效果,也可以讓程式設計師在伺服器檢視帶資料的動態頁面效果。這是由於它支援 html 原型,然後在 html 標籤裡增加額外的屬性來達到模板+資料的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 Thymeleaf 的模板可以靜態地執行;當有資料返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
  • Thymeleaf 開箱即用的特性。它提供標準和 Spring 標準兩種方言,可以直接套用模板實現 JSTL、 OGNL表示式效果,避免每天套模板、改 Jstl、改標籤的困擾。同時開發人員也可以擴充套件和建立自定義的方言。
  • Thymeleaf 提供 Spring 標準方言和一個與 SpringMVC 完美整合的可選模組,可以快速的實現表單繫結、屬性編輯器、國際化等功能。

2. 快速入門

這裡我們先正常構建一個 Spring Boot 工程: spring-boot-thymeleaf ,在 pom.xml 檔案中引入 Thymeleaf 的相關依賴,如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

工程的配置檔案 application.yml 如下:

server:
  port: 8080
spring:
  application:
    name: spring-boot-thymleaf
  thymeleaf:
    # 關閉thymeleaf快取 開發時使用 否則沒有實時畫面
    cache: false
    # 檢查模板是否存在,然後再呈現
    check-template-location: true
    # Content-Type value.
    servlet:
      content-type: text/html
    # 啟用MVC Thymeleaf檢視解析度
    enabled: true
    # Template encoding.
    encoding: UTF-8
    # 關閉嚴格模式
    mode: LEGACYHTML5
    # Prefix that gets prepended to view names when building a URL.
    prefix: classpath:/templates/
    # Suffix that gets appended to view names when building a URL.
    suffix: .html
  mvc:
    # 指定靜態資源處理路徑
    static-path-pattern: /static/**
    view:
      suffix: .html

有關 thymeleaf 都寫明瞭註釋,這裡需要注意的有以下幾點:

  • spring.thymeleaf.mode :這裡是配置當前模版的解析模式的,預設值為 HTML ,這時會開啟嚴格模式,所有的 HTML 必須有頭有尾,很多地方並不符合我們平時的書寫習慣,這裡最好關閉嚴格模式。
  • spring.thymeleaf.cache :這裡是 thymeleaf 的快取,在平時的練習中最好關閉,否則頁面修改後重新整理瀏覽器將會無效,而在生產環境中,視具體的業務場景而定。
  • spring.mvc.static-path-pattern :這裡是配置我們靜態資源的路徑,一般預設是配置 /static/** 路徑,這裡用於存放我們的 js 、 css 、圖片等靜態資源。

配置通用 404 和 500 頁面,直接在 templates\error 建立對應頁面即可,這裡可以看一下 Spring Boot 錯誤頁面轉發的原始碼 org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver,如下:

@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
    ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
    if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
        modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
    }
    return modelAndView;
}

private ModelAndView resolve(String viewName, Map<String, Object> model) {
    String errorViewName = "error/" + viewName;
    TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
            this.applicationContext);
    if (provider != null) {
        return new ModelAndView(errorViewName, model);
    }
    return resolveResource(errorViewName, model);
}

可以看到這裡會根據當前的狀態響應碼轉發到對應的頁面,路由為 error/** 。筆者這裡簡單建立兩個錯誤頁面,如圖:

建立測試 Controller ,如下:

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(HttpServletRequest request) {
        // 構建測試資料
        Map<String, Object> map = new HashMap<>();

        UserModel userModel = new UserModel();
        userModel.setId(1L);
        userModel.setName("Spring Boot");
        userModel.setAge(18);

        map.put("user", userModel);

        List<CourseModel> list = new ArrayList<>();

        for (int i = 0; i < 2; i++) {
            CourseModel courseMode = new CourseModel();
            courseMode.setId((long) i);
            courseMode.setName("Spring Boot:" + i);
            courseMode.setAddress("課程地點:" + i);
            list.add(courseMode);
        }

        map.put("list", list);

        map.put("flag", true);

        request.setAttribute("data", map);
        return "hello";
    }
}

在此註冊測試類中,進行資料初始化並輸出至頁面。

  • Thymeleaf 預設的模板路徑 src/main/resources/templates ,只需要在這個這個路徑下編寫模版檔案即可。

Thymeleaf 模版檔案如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Hello Spring Boot</title>
    <link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}">
</head>
<body>
<div class="container">
    <div>使用者資訊:</div>
    <table class="table table-dark">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">姓名</th>
            <th scope="col">年齡</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <th scope="row" th:text="${data.user.id}"></th>
            <td th:text="${data.user.name}"></td>
            <td th:text="${data.user.age}"></td>
        </tr>
        </tbody>
    </table>
    <div>課程資訊:</div>
    <table class="table table-dark">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">課程名稱</th>
            <th scope="col">課程地點</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="course, iterStat : ${data.list}">
            <th scope="row" th:text="${course.id}"></th>
            <td th:text="${course.name}"></td>
            <td th:text="${course.address}"></td>
        </tr>
        </tbody>
    </table>

    <div th:if="${data.flag == true}">如果 flag 為 true 你將可以看到這行字:)</div>

</div>

</body>
</html>

Thymeleaf 部分常用 th 標籤如下:

關鍵字 功能介紹 案例
th:id 替換id <input th:id="'xxx' + ${collect.id}"/>
th:text 文字替換 <p th:text="${collect.description}">description</p>
th:utext 支援html的文字替換 <p th:utext="${htmlcontent}">conten</p>
th:object 替換物件 <div th:object="${session.user}">
th:value 屬性賦值 <input th:value="${user.name}" />
th:with 變數賦值運算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 設定樣式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 點選事件 th:onclick="'getCollect()'"
th:each 屬性賦值 tr th:each="user,userStat:${users}">
th:if 判斷條件 <a th:if="${userId == collect.userId}" >
th:unless 和th:if判斷相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href 連結地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch 多路選擇 配合th:case 使用 <div th:switch="${user.role}">
th:case th:switch的一個分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 佈局標籤,定義一個程式碼片段,方便其它地方引用 <div th:fragment="alert">
th:include 佈局標籤,替換內容到引入的檔案 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 佈局標籤,替換整個標籤到引入的檔案 <div th:replace="fragments/header :: title"></div>
th:selected selected選擇框 選中 th:selected="(${xxx.id} == ${configObj.dd})"
th:src 圖片類地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline 定義js指令碼可以使用變數 <script type="text/javascript" th:inline="javascript">
th:action 表單提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:remove 刪除某個屬性 <tr th:remove="all"> 1.all:刪除包含標籤和所有的孩子。2.body:不包含標記刪除,但刪除其所有的孩子。3.tag:包含標記的刪除,但不刪除它的孩子。4.all-but-first:刪除所有包含標籤的孩子,除了第一個。5.none:什麼也不做。這個值是有用的動態評估。
th:attr 設定標籤屬性,多個屬性可以用逗號分隔 比如 th:attr="src=@{/image/aa.jpg},title=#{logo}" ,此標籤不太優雅,一般用的比較少。

3. 測試

啟動當前工程,開啟瀏覽器訪問路徑: http://localhost:8080/hello ,結果如圖:

5. 程式碼示例

示例程式碼-Github

示例程式碼-Gitee

6. 參考

《Thymeleaf 使用詳解