Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)

號外:為讀者持續整理了幾份最新教程,覆蓋了 Spring Boot、Spring Cloud、微服務架構等PDF。

獲取方式:關注右側公眾號"泥瓦匠BYSocket",來領取吧!


文章工程:

* 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 自然更加推薦。

結構

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

Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)

目錄如下

  • 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>

<dependency>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-starter-webflux/<artifactid>

<dependency>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-starter-thymeleaf/<artifactid>

<dependency>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-starter-test/<artifactid>

<scope>test/<scope>

<dependency>

<groupid>junit/<groupid>

<artifactid>junit/<artifactid>

<version>4.12/<version>

這裡我們增加了 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;
}
/<city>/<string>

解釋下語法:

  • 返回值 Mono 或者 String 都行,但是 Mono 代表著我這個返回 View 也是回調的。
  • return 字符串,該字符串對應的目錄在 resources/templates 下的模板名字。
  • Model 對象來進行數據綁定到視圖
  • 一般會集中用常量管理模板視圖的路徑

Tymeleaf 視圖

然後編寫兩個視圖 hello 和 cityList,代碼分別如下:

hello.html:





<title>歡迎頁面/<title>


你好,歡迎來自




cityList.html:





<title>城市列表/<title>



<table>

<legend>
城市列表
/<legend>
<thead>

城市編號
省份編號
名稱
描述

/<thead>
<tbody>






/<tbody>
/<table>



常用語法糖如下

  • ${…} 變量表達式
  • 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 ,可以看到如圖的響應:

Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)

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

Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)

總結

這裡,探討了 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。加入純技術交流群,成長技術)


分享到:


相關文章: