【SpringBoot實戰】視圖技術-Thymeleaf

前言

在一個Web應用中,通常會採用MVC設計模式實現對應的模型、視圖和控制器,其中,視圖是用戶看到並與之交互的界面。對最初的Web應用來說,視圖是由HTML元素組成的靜態界面;而後期的Web應用更傾向於使用動態模板技術,從而實現前後端分離和頁面的動態數據展示。Spring Boot框架為簡化項目的整體開發,提供了一些視圖技術支持,並主要推薦整合模板引擎技術實現前端頁面的動態化內容。本文對SpringBoot常用的Thymeleaf進行整合。

Thymeleaf基本語法

Thymeleaf是一種現代的基於服務器端的Java模板引擎技術,也是一個優秀的面向Java的XML、XHTML、HTML5頁面模板,它具有豐富的標籤語言、函數和表達式,在使用Spring Boot框架進行頁面設計時,一般會選擇 Thymeleaf模板。我們在這裡學習Thymeleaf 常用的標籤、表達式。

常用標籤

標籤

Thymeleaf標籤

th:標籤 說明
th:insert 頁面片段包含(類似JSP中的include標籤)
th:replace 頁面片段包含(類似JSP中的include標籤)
th:each 元素遍歷(類似JSP中的c:forEach標籤)
th:if 條件判斷,條件成立時顯示th標籤內容
th:unless 條件判斷,條件不成立時顯示內容
th:switch 條件判斷,進行選擇性匹配
th:case th:switch分支,選擇的元素
th:object 用於替換對象
th:with 用於定義局部遍歷
th:attr 用於屬性修改
th:attrprepend 通用屬性修改,將計算結果追加前綴到現有屬性值
th:attrappend 通用屬性修改,將計算的結果追加後綴現有屬性值
th:value 屬性值修改,指定標籤屬性值
th:href 用於設定鏈接地址
th:src 用於設定鏈接地址
th:text 用於指定標籤顯示文本內容
th:utext 用於指定標籤顯示內容,對特殊標籤不轉譯
th:fragment 聲明片段
th:removve 移除片段

如何使用標籤

使用標籤只需要加上一個命名空間就可以了。<html lang="en" xmlns:th="//thymeleaf.org"> 即修改原html的第二行就可以了。

<!DOCTYPE html>

<html xmlns:th="//www.thymeleaf.org">

  <head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" 
          href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  </head>

  <body>
  
    <p th:text="#{home.welcome}">Welcome to our grocery store!</p>
  
  </body>

</html>

標準表達式

表達式 說明
${..} 變量表達式
*{..} 選擇變量表達式
#{..} 消息表達式
@{..} 鏈接URL表達式
~{..} 片段表達式

變量表達式

變量表達式${..}主要用於獲取上下文中的變量值,示例代碼如下。

這是標題

– 使用了Thymeleaf模板的變量表達式${..}用來動態獲取p標籤中的內容
– 如果當前程序沒有啟動或者當前上下文中不存在title變量,該片段會顯示標籤默認值「這是標題」;
– 如果當前上下文中存在title 變量並且程序已經啟動,當前p標籤中的默認文本內容將會被tite變量的值所替換,從而達到模板引擎頁面數據動態替換的效果。


Thymeleaf為變量所在域提供了一些內置對象

內置對象 說明
#ctx 上下文對象
#vars 上下文變量
#locale 上下文區域設置
#request (僅限 Web Context)HttpServletRequest 對象
#response (僅限Web Context)HttpServletResponse 對象
#session 僅限Web Context) HttpSession對象
#servletContext (僅限 Web Context)ServletContext 對象

結合上述內置對象的說明,假設要在Thymeleaf模板擎頁面中動態獲取當前國家信息,可以使用#locale內置對象

<span th:text="${#locale.country}">China</span>

選擇變量表達式

選擇交量表達式和變量表達式用法類似,一般用於從被選定對象而不是上下文中獲取屬性值,如果沒有選定對象,則和變量表達式一樣,示例代碼如下。

<div th:object="$(session.user)">
    <p>Name: <span th:text="s(object.firstName)">Sebastiahk</span></p>
    <p>username:<span th:text="$(session.user,lastName)">Pepper</span></p>
    <p>Nationality:<span th:text="*(nationality)">Saturn</span>.</p> 
</div>
  • ${#object.firstName}變量表達式使用Thymeleaf模板提供的內置對象object獲取當前上下文對象中的frstName屬性值;
  • ¥{session.user.lastName}變量表達式獲取當前user對象的lastName屬性值;
  • *{nationality}選擇變量表達式獲取當前指定對象user的nationality屬性值。

消息表達式

消息表達式#{..}主要用於Thymeleaf模板頁面國際化內容的動態替換和展示。使用消息表這式#{..}進行國際化設置時,還需要提供一些國際化配置文件。關於消息表達式的使用,下文寫國際化時會詳細說明。

鏈接表達式

鏈接表達式@{..}一般用於頁面跳轉或者資源的引入,在Web開發中佔據着非常重要的地位,並且使用也非常頻繁。

<a href="details.html" th:href="@{http:localhost:8080/gtvg/order/details(order=$o.id})}">view</a>
<a href="details.html" th:href="@{/order/details(order=$o.id})}">view</a>
  • @{..}分別編寫了絕對鏈接地址和相對鏈接地址。
  • 在有參表達式中,需要按照@(路徑(參數名稱=參數值.參數名稱=參數值..))的形式編寫,同時該參數的值可以使用變量表達式來傳遞動態參數值。

片段表達式

片段表達式~{..}是一種用來將標記片段移動到模板中的方法。其中,最常見的用法是使用th:insert或th:replace 屬性插入片段

<div th:insert="~(thymeleafDemo::title】"></div>
  • th:insert屬性將title片段模板引用到該
    標籤中。
  • thymelcafDemo為模板名稱,Thymeleal會自動查找「classpathy/resources/templates/」目錄下的thymeleaDemo模板,title為聲明的片段名稱。

Thyemleaf基本使用

靜態資源訪問

Spring Boot默認設置了靜態資源的訪問路徑,默認將/**所有訪問映射到以下目錄。

  • classpath:/META-INF/resources/:項目類路徑下的META-INF文件夾下的resources文件夾下的所有文件。
  • classpath:/resources/:項目類路徑下的resources文件夾下的所有文件。
  • classpath:/static/:項目類路徑下的static文件夾下的所有文件。
  • classpath:/public/:項目類路徑下的public文件夾下的所有文件。
  • Spring Initializr 方式創建的 Spring Boot 項目會默認生成一個 resources目錄,在resources目錄中新建public、resources、static3個子目錄,Spring Boot默認會依次從public、resources、static裏面查找靜態資源。

Thymeleaf頁面展示

我們創建一個springboot項目用於本次實驗。項目名為springboot_01_thyme。java8,springboot2.6.6

導入Thymeleaf依賴

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

編寫配置文件


# thymeleaf cache
spring.thymeleaf.cache=false

spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

創建WEB控制類

創建一個LoginController類用於數據替換效果測試。

package com.hjk.controller;

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

import java.util.Calendar;

@Controller
public class LoginController {
    @GetMapping("toLoginPage")
    public String toLoginPage(Model model){
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }

}

創建模板頁面並引入靜態資源

我們寫一個login.html進行測試。我們導入一個bootstrap的樣式到static/login裏面,並且自己定義一些css。

<!DOCTYPE html>
<html lang="en" xmlns:th="//www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
    <title>用戶登錄界面</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
   <style type="text/css">
    html,
    body {
    height: 100%;
    }
    body {
    align-items: center;
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: greenyellow;
    }
    .form-signin {
        width: 100%;
        max-width: 330px;
        padding: 15px;
        margin: 0 auto;
    }
    </style>

</head>
<body class="text-center">
<!--  用戶登錄form表單 -->
<form class="form-signin">
    <h1 class="h3 mb-3 font-weight-normal">請登錄</h1>
    <input type="text" placeholder="用戶名">
    <input type="password" placeholder="密碼">
    <div>
        <label>
            <input type="checkbox" value="remember-me"> 記住我
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit">登錄</button>
    <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2018</span>-<span th:text="${currentYear}+1">2019</span></p>
</form>
</body>
</html>

  • 我們使用xmlns:th="//thymeleaf.org"引入Thymeleaf標籤
  • 通過th:href引入外聯css
  • 通過th:text後台動態傳遞年份currentYear

最後我們通過訪問//localhost:8080/toLoginPage 可以查看效果

配置國際化頁面

編寫多語言配置文件

在resources目錄下創建名為i18n的文件夾,數一數這個單詞多少個字母internationalization,就知道為什麼叫i18n了。
然後我們在i18n文件夾下面創建login.properties、 login_zh_CN.properties、 login_en_US.properties文件。
目錄結構:這個Resource Bundle ‘login’時idea自動創建的,我們不需要管,只需要完成我們的就行。
image

login.properties

login.tip=請登錄
login.username=用戶名
login.password=密碼
login.rememberme=記住我
login.button=登錄

login_zh_CN.properties

login.tip=請登錄
login.username=用戶名
login.password=密碼
login.rememberme=記住我
login.button=登錄

login_en_US.properties

login.tip=Please sign in
login.username=Username
login.password=Password
login.rememberme=Rememberme
login.button=Login

然後我們在配置文件application.properties裏面添加代碼

  • 這個是我們必須要寫的,login是我們的語言文件前綴,springboot默認前綴是messages,所以不寫識別不了。
    spring.messages.basename=i18n.login

定製區域信息解析器

我們在config包下面創建一個MyLocalResovel類,自定義國際化功能區域信息解析器。

package com.hjk.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Configuration
public class MyLocalResovel implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String parameter = request.getParameter("1");
        String header = request.getHeader("Accept-Language");
        Locale locale = null;
        if (!StringUtils.isEmpty(parameter)){
            String[] s = parameter.split("_");
            locale = new Locale(s[0], s[1]);
        }else{
            String[] split = header.split(",");
            String[] split1 = split[0].split("-");
            locale = new Locale(split1[0],split1[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
    
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalResovel();
    }
    
}
  • 注意分割符的兩個下滑線,不一樣

重寫login.html實現國際化

<!DOCTYPE html>
<html lang="en" xmlns:th="//www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
    <title>用戶登錄界面</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
   <style type="text/css">
    html,
    body {
    height: 100%;
    }
    body {
    align-items: center;
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: greenyellow;
    }
    .form-signin {
        width: 100%;
        max-width: 330px;
        padding: 15px;
        margin: 0 auto;
    }
    </style>

</head>
<body class="text-center">
<!--  用戶登錄form表單 -->
<form class="form-signin">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">請登錄</h1>
    <input type="text" th:placeholder="#{login.username}">
    <input type="password" th:placeholder="#{login.password}" \>
    <div>
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">登錄</button>
    <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2018</span>-<span th:text="${currentYear}+1">2019</span></p>
    <a class="btn btn-sm" th:href="@{/toLoginPage(1='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/toLoginPage(1='en_US')}">English</a>
</form>
</body>
</html>

這裡我們基本就完成了,但是在訪問中文的時候會出現亂碼現象。

我們打開idea的file->settings->file Encodings.
將Default encoding for properties的編碼改為utf-8,同時勾選Transparentnative-to-ascii conversion
image

然後我們重新編寫login.properties和其他相關的

login.tip=請登錄
login.username=用戶名
login.password=密碼
login.rememberme=記住我
login.button=登錄

但是這種方法1隻對當前項目有效。下次創建還是使用GBK編碼

總結

本文我們主要了解了Thymeleaf的基本語法、標籤、表達式、基本使用、同時還實現了頁面登錄頁得國際化。

….