1. 程式人生 > >Spring Boot 2 快速教程:WebFlux 整合 Thymeleaf(五)

Spring Boot 2 快速教程:WebFlux 整合 Thymeleaf(五)

號外:為讀者持續整理了幾份最新教程,覆蓋了 Spring Boot、Spring Cloud、微服務架構等PDF。
獲取方式:關注右側公眾號"泥瓦匠BYSocket",來領取吧!


摘要: 原創出處 https://www.bysocket.com 「公眾號:泥瓦匠BYSocket 」歡迎關注和轉載,保留摘要,謝謝!

這是泥瓦匠的第105篇原創

文章工程:
* JDK 1.8
* Maven 3.5.2
* Spring Boot 2.1.3.RELEASE
* 工程名:springboot-webflux-4-thymeleaf
* 工程地址:見文末

前言

上一講,我們用 MongoDB 來實現 WebFlux 對資料來源的操作。那麼有了資料需要渲染到前臺給使用者展示。這就是本文關心的 View 層。View 的表現形式有很多,比如 JSON 和 HTML。開發中常用模板語言很常見的有 Thymeleaf、Freemarker等。那

什麼是模板語言?

常見的模板語言都包含以下幾個概念:資料(Data)、模板(Template)、模板引擎(Template Engine)和結果文件(Result Documents)。

  • 資料

資料是資訊的表現形式和載體,可以是符號、文字、數字、語音、影象、視訊等。資料和資訊是不可分離的,資料是資訊的表達,資訊是資料的內涵。資料本身沒有意義,資料只有對實體行為產生影響時才成為資訊。

  • 模板

模板,是一個藍圖,即一個與型別無關的類。編譯器在使用模板時,會根據模板實參對模板進行例項化,得到一個與型別相關的類。

  • 模板引擎

模板引擎(這裡特指用於Web開發的模板引擎)是為了使使用者介面與業務資料(內容)分離而產生的,它可以生成特定格式的文件,用於網站的模板引擎就會生成一個標準的HTML文件。

  • 結果文件

一種特定格式的文件,比如用於網站的模板引擎就會生成一個標準的HTML文件。

模板語言用途廣泛,常見的用途如下:

  • 頁面渲染
  • 文件生成
  • 程式碼生成
  • 所有 “資料+模板=文字” 的應用場景

Spring Boot 推薦使用的模板語言是 Thymeleaf,那

什麼是 Thymeleaf?

官方的解釋如下:

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf 是現代的模板語言引擎,可以獨立執行也可以服務於 Web。主要目標是為開發提供天然的模板,並且能在 HTML 裡面準確的顯示。

Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 後推薦使用。目前是 Spring 5 自然更加推薦。

結構

類似上面講的工程搭建,新建一個工程編寫此案例。工程如圖:

目錄如下

  • org.spring.springboot.webflux.controller – Controller 層
  • org.spring.springboot.dao – 資料操作層 DAO
  • org.spring.springboot.domain – 實體類
  • org.spring.springboot.handler – 業務邏輯層
  • Application – 應用啟動類
  • application.properties – 應用配置檔案
  • pom.xml maven 配置
  • application.properties 配置檔案

模板是會用到下面兩個目錄

  • static 目錄是存放 CSS、JS 等資原始檔
  • templates 目錄是存放檢視

本文重點在 Controller 層 和 templates 檢視的編寫。

新增 POM 依賴與配置

在 pom.xml 配置新的依賴:

  <dependencies>

    <!-- Spring Boot Web Flux 依賴 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <!-- 模板引擎 Thymeleaf 依賴 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>


    <!-- Spring Boot Test 依賴 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- Junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

這裡我們增加了 Thymeleaf 依賴,但不用在 application.properties – 應用配置檔案 配置人任何配置。預設啟動其預設配置,如需修改配置參考 Thymeleaf 依賴配置,如下:

spring.thymeleaf.cache=true # Enable template caching.
spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

包括常用的 編碼、是否開啟快取等等。

WebFlux 中使用 Thymeleaf

在 CityWebFluxController 控制層,新增兩個方法如下:

    @GetMapping("/hello")
    public Mono<String> hello(final Model model) {
        model.addAttribute("name", "泥瓦匠");
        model.addAttribute("city", "浙江溫嶺");

        String path = "hello";
        return Mono.create(monoSink -> monoSink.success(path));
    }

    private static final String CITY_LIST_PATH_NAME = "cityList";

    @GetMapping("/page/list")
    public String listPage(final Model model) {
        final Flux<City> cityFluxList = cityHandler.findAllCity();
        model.addAttribute("cityList", cityFluxList);
        return CITY_LIST_PATH_NAME;
    }

解釋下語法:

  • 返回值 Mono 或者 String 都行,但是 Mono 代表著我這個返回 View 也是回撥的。
  • return 字串,該字串對應的目錄在 resources/templates 下的模板名字。
  • Model 物件來進行資料繫結到檢視
  • 一般會集中用常量管理模板檢視的路徑

Tymeleaf 檢視

然後編寫兩個檢視 hello 和 cityList,程式碼分別如下:

hello.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <title>歡迎頁面</title>
</head>

<body>

<h1 >你好,歡迎來自<p th:text="${city}"></p>的<p th:text="${name}"></p></h1>

</body>
</html>

cityList.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <title>城市列表</title>
</head>

<body>

<div>


    <table>
        <legend>
            <strong>城市列表</strong>
        </legend>
        <thead>
        <tr>
            <th>城市編號</th>
            <th>省份編號</th>
            <th>名稱</th>
            <th>描述</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="city : ${cityList}">
            <td th:text="${city.id}"></td>
            <td th:text="${city.provinceId}"></td>
            <td th:text="${city.cityName}"></td>
            <td th:text="${city.description}"></td>
        </tr>
        </tbody>
    </table>

</div>

</body>
</html>

常用語法糖如下

  • ${…} 變量表達式
  • th:text 處理 Tymeleaf 表示式
  • th:each 遍歷表示式,可遍歷的物件:實現java.util.Iterable、java.util.Map(遍歷時取java.util.Map.Entry)、array 等

還有很多使用參考官方方文件 http://www.thymeleaf.org/documentation.html

執行工程

下面執行工程驗證下。使用 IDEA 右側工具欄,點選 Maven Project Tab ,點選使用下 Maven 外掛的 install 命令。或者使用命令列的形式,在工程根目錄下,執行 Maven 清理和安裝工程的指令:

cd springboot-webflux-4-thymeleaf
mvn clean install

在控制檯中看到成功的輸出:

... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2017-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------

在 IDEA 中執行 Application 類啟動,任意正常模式或者 Debug 模式。可以在控制檯看到成功執行的輸出:

... 省略
2018-04-10 08:43:39.932  INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext     : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935  INFO 2052 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2018-04-10 08:43:39.960  INFO 2052 --- [           main] org.spring.springboot.Application        : Started Application in 6.547 seconds (JVM running for 9.851)

開啟瀏覽器,訪問 http://localhost:8080/city/hello ,可以看到如圖的響應:

繼續訪問 http://localhost:8080/city/page/list , 發現沒有值,那麼按照上一講插入幾條資料即可有值,如圖:

總結

這裡,探討了 Spring WebFlux 的如何整合 Thymeleaf 。整合其他模板語言 Thymeleaf、Freemarker,就大同小異了。下面,我們能會整合 Thymeleaf 和 MongoBD,實現一個整體的簡單案例。

程式碼示例

本文示例讀者可以通過檢視下面倉庫的中的模組工程名: 2-x-spring-boot-webflux-handling-errors:

  • Github:https://github.com/JeffLi1993/springboot-learning-example
  • Gitee:https://gitee.com/jeff1993/springboot-learning-example

如果您對這些感興趣,歡迎 star、follow、收藏、轉發給予支援!

參考資料

  • Spring Boot 2.x WebFlux 系列:https://www.bysocket.com/archives/2290
  • spring.io 官方文件

以下專題教程也許您會有興趣

  • 《程式兵法:演算法與資料結構》 https://www.bysocket.com/technique/2314.html
  • 《Spring Boot 2.x 系列教程》
    https://www.bysocket.com/springboot
  • 《Java 核心系列教程》
    https://www.bysocket.com/technique/2100.html

​ 
(關注微信公眾號,領取 Java 精選乾貨學習資料) 
(新增我微信:bysocket01。加入純技術交流群,成長技