天天看點

【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="http://thymeleaf.org">

即修改原html的第二行就可以了。

<!DOCTYPE html>

<html xmlns:th="http://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="http://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="http://thymeleaf.org"

    引入Thymeleaf标簽
  • 通過th:href引入外聯css
  • 通過th:text背景動态傳遞年份currentYear

最後我們通過通路http://localhost:8080/toLoginPage 可以檢視效果

配置國際化頁面

編寫多語言配置檔案

在resources目錄下建立名為i18n的檔案夾,數一數這個單詞多少個字母internationalization,就知道為什麼叫i18n了。

然後我們在i18n檔案夾下面建立login.properties、 login_zh_CN.properties、 login_en_US.properties檔案。

目錄結構:這個Resource Bundle 'login'時idea自動建立的,我們不需要管,隻需要完成我們的就行。

【SpringBoot實戰】視圖技術-Thymeleaf

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="http://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

【SpringBoot實戰】視圖技術-Thymeleaf

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

login.tip=請登入
login.username=使用者名
login.password=密碼
login.rememberme=記住我
login.button=登入
           

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

總結

本文我們主要了解了Thymeleaf的基本文法、标簽、表達式、基本使用、同時還實作了頁面登入頁得國際化。

....