1. 程式人生 > >極簡 Spring Boot 整合 Thymeleaf 頁面模板

極簡 Spring Boot 整合 Thymeleaf 頁面模板

雖然現在慢慢在流行前後端分離開發,但是據鬆哥所瞭解到的,還是有一些公司在做前後端不分的開發,而在前後端不分的開發中,我們就會需要後端頁面模板(實際上,即使前後端分離,也會在一些場景下需要使用頁面模板,例如郵件傳送模板)。

早期的 Spring Boot 中還支援使用 Velocity 作為頁面模板,現在的 Spring Boot 中已經不支援 Velocity 了,頁面模板主要支援 Thymeleaf 和 Freemarker ,當然,作為 Java 最最基本的頁面模板 Jsp ,Spring Boot 也是支援的,只是使用比較麻煩。

鬆哥打算用三篇文章分別向大家介紹一下這三種頁面模板技術。

今天我們主要來看看 Thymeleaf 在 Spring Boot 中的整合!

Thymeleaf 簡介

Thymeleaf 是新一代 Java 模板引擎,它類似於 Velocity、FreeMarker 等傳統 Java 模板引擎,但是與傳統 Java 模板引擎不同的是,Thymeleaf 支援 HTML 原型。

它既可以讓前端工程師在瀏覽器中直接開啟檢視樣式,也可以讓後端工程師結合真實資料檢視顯示效果,同時,SpringBoot 提供了 Thymeleaf 自動化配置解決方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。

事實上, Thymeleaf 除了展示基本的 HTML ,進行頁面渲染之外,也可以作為一個 HTML 片段進行渲染,例如我們在做郵件傳送時,可以使用 Thymeleaf 作為郵件傳送模板。

另外,由於 Thymeleaf 模板字尾為 .html,可以直接被瀏覽器開啟,因此,預覽時非常方便。

整合

  • 建立專案

Spring Boot 中整合 Thymeleaf 非常容易,只需要建立專案時新增 Thymeleaf 即可:

建立完成後,pom.xml 依賴如下:

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

當然,Thymeleaf 不僅僅能在 Spring Boot 中使用,也可以使用在其他地方,只不過 Spring Boot 針對 Thymeleaf 提供了一整套的自動化配置方案,這一套配置類的屬性在 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 中,部分原始碼如下:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
        private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
        public static final String DEFAULT_PREFIX = "classpath:/templates/";
        public static final String DEFAULT_SUFFIX = ".html";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = DEFAULT_PREFIX;
        private String suffix = DEFAULT_SUFFIX;
        private String mode = "HTML";
        private Charset encoding = DEFAULT_ENCODING;
        private boolean cache = true;
        //...
}
  1. 首先通過 @ConfigurationProperties 註解,將 application.properties 字首為 spring.thymeleaf 的配置和這個類中的屬性繫結。
  2. 前三個 static 變數定義了預設的編碼格式、檢視解析器的字首、字尾等。
  3. 從前三行配置中,可以看出來,Thymeleaf 模板的預設位置在 resources/templates 目錄下,預設的字尾是 html
  4. 這些配置,如果開發者不自己提供,則使用 預設的,如果自己提供,則在 application.properties 中以 spring.thymeleaf 開始相關的配置。

而我們剛剛提到的,Spring Boot 為 Thymeleaf 提供的自動化配置類,則是 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration ,部分原始碼如下:

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}

可以看到,在這個自動化配置類中,首先匯入 ThymeleafProperties ,然後 @ConditionalOnClass 註解表示噹噹前系統中存在 TemplateModeSpringTemplateEngine 類時,當前的自動化配置類才會生效,即只要專案中引入了 Thymeleaf 相關的依賴,這個配置就會生效。

這些預設的配置我們幾乎不需要做任何更改就可以直接使用了。如果開發者有特殊需求,則可以在 application.properties 中配置以 spring.thymeleaf 開頭的屬性即可。

  • 建立 Controller

接下來我們就可以建立 Controller 了,實際上引入 Thymeleaf 依賴之後,我們可以不做任何配置。新建的 IndexController 如下:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId((long) i);
            u.setName("javaboy:" + i);
            u.setAddress("深圳:" + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "index";
    }
}
public class User {
    private Long id;
    private String name;
    private String address;
    //省略 getter/setter
}

IndexController 中返回邏輯檢視名+資料,邏輯檢視名為 index ,意思我們需要在 resources/templates 目錄下提供一個名為 index.htmlThymeleaf 模板檔案。

  • 建立 Thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>編號</td>
        <td>使用者名稱</td>
        <td>地址</td>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.address}"></td>
    </tr>
</table>
</body>
</html>

Thymeleaf 中,通過 th:each 指令來遍歷一個集合,資料的展示通過 th:text 指令來實現,

注意 index.html 最上面要引入 thymeleaf 名稱空間。

配置完成後,就可以啟動專案了,訪問 /index 介面,就能看到集合中的資料了:

另外,Thymeleaf 支援在 js 中直接獲取 Model 中的變數。例如,在 IndexController 中有一個變數 username

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("username", "李四");
        return "index";
    }
}

在頁面模板中,可以直接在 js 中獲取到這個變數:

<script th:inline="javascript">
    var username = [[${username}]];
    console.log(username)
</script>

這個功能算是 Thymeleaf 的特色之一吧。

手動渲染

前面我們說的是返回一個 Thymeleaf 模板,我們也可以手動渲染 Thymeleaf 模板,這個一般在郵件傳送時候有用,例如我在 resources/templates 目錄下新建一個郵件模板,如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>hello 歡迎 <span th:text="${username}"></span>加入 XXX 集團,您的入職資訊如下:</p>
<table border="1">
    <tr>
        <td>職位</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>薪水</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
<img src="http://www.javaboy.org/images/sb/javaboy.jpg" alt="">
</body>
</html>

這一個 HTML 模板中,有幾個變數,我們要將這個 HTML 模板渲染成一個 String 字串,再把這個字串通過郵件傳送出去,那麼如何手動渲染呢?

@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
    Context context = new Context();
    context.setVariable("username", "javaboy");
    context.setVariable("position", "Java工程師");
    context.setVariable("salary", 99999);
    String mail = templateEngine.process("mail", context);
    //省略郵件傳送
}
  1. 渲染時,我們需要首先注入一個 TemplateEngine 物件,這個物件就是在 Thymeleaf 的自動化配置類中配置的(即當我們引入 Thymeleaf 的依賴之後,這個例項就有了)。
  2. 然後構造一個 Context 物件用來存放變數。
  3. 呼叫 process 方法進行渲染,該方法的返回值就是渲染後的 HTML 字串,然後我們將這個字串傳送出去。

這是 Spring Boot 整合 Thymeleaf 的幾個關鍵點,關於 Thymeleaf 這個頁面模板本身更多的用法,大家可以參考 Thymeleaf 的文件:https://www.thymeleaf.org。

總結

本文主要向大家簡單介紹了 Spring Boot 和 Thymeleaf 整合時的幾個問題,還是比較簡單的,大家可以閱讀 Thymeleaf 官方文件學習 Thymeleaf 的更多用法。本文案例我已上傳到 GitHub ,歡迎大家 star :https://github.com/lenve/javaboy-code-samples

關於本文,有問題歡迎留言討論。
關注公眾號牧碼小子,專注於 Spring Boot+微服務以及前後端分離等全棧技術,定期視訊教程分享,關注後回覆 Java ,領取鬆哥為你精心準備的 Java 乾貨!

相關推薦

Spring Boot 整合 Thymeleaf 頁面模板

雖然現在慢慢在流行前後端分離開發,但是據鬆哥所瞭解到的,還是有一些公司在做前後端不分的開發,而在前後端不分的開發中,我們就會需要後端頁面模板(實際上,即使前後端分離,也會在一些場景下需要使用頁面模板,例如郵件傳送模板)。 早期的 Spring Boot 中還支援使用 Velocity 作為頁面模板,現在的

Spring Boot 整合 Thymeleaf 模板引擎

原文地址:Spring Boot 整合 Thymeleaf 模板引擎 Thymeleaf 是適用於 Web 和獨立環境的現代伺服器端 Java 模板引擎。 Thymeleaf 的主要目標是為開發帶來優雅的模板 - Thymeleaf 模板對於瀏覽器來說這些非HTML標準屬性在渲染

Spring Boot整合Thymeleaf模板引擎

一、Thymeleaf 模板介紹 Spring Boot 推薦使用Thymeleaf 來代替傳統開發中的JSP,那麼什麼是Thymeleaf 模板引擎呢?下面就來簡單的介紹一下。 1.1什麼是Thymeleaf Thymeleaf 是一款用於渲

Spring boot 整合Thymeleaf

前言 上一篇介紹了Spring Boot中整合Jsp,儘管Spring boot官方並不推薦使用Jsp~ 這篇文章將介紹如何整合官方所推薦的Thymeleaf模板引擎 簡單瞭解 首先新建專案,選擇模板引擎時,會有四個可以選擇 至於JSP技術Spring Boot官方

Spring Boot整合thymeleaf使用、thymeleaf常用標籤、thymeleaf常用語法

Spring Boot 推薦使用 Thymeleaf 來代替 JSP,Thymeleaf 模板到底是什麼來頭呢,下面我們來聊聊。 Thymeleaf 介紹 Thymeleaf 是一款用於渲染 XML/XHTML/HTML 5 內容的模板引擎。類似 JSP、Velocity、FreeMaker

Spring Boot整合Thymeleaf實戰筆記,系統學習Thymeleaf

Thymeleaf1.理解:(1)Thymeleaf是一款Java模板引擎,類似於JSP,Freemarker,能夠處理html,xml,javaScript,Css甚至純文字;(2)自然模板,原型即頁面(3)語法優雅易懂,OGNL,SpringEL(4)使用web標準,支援HTML52.Thymeleaf標

Spring Boot整合Thymeleaf簡單例項

1、定義 Thymeleaf是一種用於Web和獨立環境的現代伺服器端的Java模板引擎。 2、簡單例項 (1)目錄結構 (2)MySpringBootApplication.java pa

Spring Boot 整合 Thymeleaf 完整 Web 案例

原創出處  作者:泥瓦匠BYSocket 希望轉載,保留摘要,謝謝! Thymeleaf 是一種模板語言。那模板語言或模板引擎是什麼?常見的模板語言都包含以下幾個概念:資料(Data)、模板(Template)、模板引擎(Template Engine)和結果文件(Result Documen

Spring boot整合Swagger2頁面 不顯示的3個常見原因

第一種原因 我遇到兩次 如下圖;解決方法    1:<dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox

spring bootthymeleaf頁面傳參兩種方式

1.利用ModelAndView物件向頁面傳參 @RequestMapping("/index/{p}.html")public ModelAndView  index(@PathVariable i

Spring Boot2 系列教程(九)Spring Boot 整合 Thymeleaf

雖然現在慢慢在流行前後端分離開發,但是據鬆哥所瞭解到的,還是有一些公司在做前後端不分的開發,而在前後端不分的開發中,我們就會需要後端頁面模板(實際上,即使前後端分離,也會在一些場景下需要使用頁面模板,例如郵件傳送模板)。 早期的 Spring Boot 中還支援使用 Velocity 作為頁面模板,現在的

Spring Boot整合模板引擎(Thymeleaf、Freemarker、jsp)

1. Thymeleaf模板 1.1 在pom.xml中新增Thymeleaf依賴 <!--使用thymeleaf標籤--> <dependency> <groupId>org.springframework.boot</groupId>

Spring Boot 整合模板引擎(jsp、Freemarker 、Thymeleaf

整合JSP模板   新增依賴 建立 maven 工程,在 pom.xml 檔案中新增如下依賴: <dependency> <groupId>javax.servlet</groupId> <artifactId>

Spring Boot 整合模板引擎(jsp、Freemarker 、Thymeleaf

整合JSP模板 新增依賴 建立 maven 工程,在 pom.xml 檔案中新增如下依賴: <dependency> <groupId>javax.servlet</groupId> <artifactId>

Spring Boot 構建企業級部落格學習(四)- Spting Boot 整合Thymeleaf模板

Spting Boot 整合Thymeleaf模板  理解Thymeleaf的概念、用法 Thymeleaf 與 Spring Boot 整合 Thymeleaf 實戰 Thymeleaf概念 理解Thymeleaf Thymeleaf是一種

Spring Boot使用thymeleaf模板時報異常:template might not exist or might not be accessible by any of the configured Template Resolvers

logs pla 開頭 spring 方法 temp ring mode acc 錯誤如下: template might not exist or might not be accessible by any of the configured Template R

Spring boot 整合spring Data JPA+Spring Security+Thymeleaf框架(上)

current 不可 src rac 分享圖片 正在 html AC ren 近期上班太忙所以耽擱了給大家分享實戰springboot 框架的使用。 以下是spri

SpringBoot訪問NoSQL和簡單的Thymeleaf-Spring-Spring-boot整合

spring context 優點 dna jdbc sys hand local tid SpringBoot訪問NoSQL SpringBoot訪問Redis 在pom.xml添加boot-data-redis定義 <parent>

Spring Boot使用Thymeleaf模板引擎渲染web檢視

Spring Boot開發Web應用 原創   2018-04-03  宗野   Spring Boot Spring Boot快速入門中我們完成了一個簡單的RESTfu

spring boot使用freemarker頁面獲取系統路徑最配置

1、配置application.properties(最後一句起作用,前面湊數的) spring.freemarker.template-loader-path=classpath:/templates/ spring.freemarker.suffix=.ftl spring.fr