上一篇介紹的是用 MongoDB 來實現 WebFlux 對數據源的操做,那麼有了數據須要渲染到前臺給用戶展現,這就是本文關心的 View 層,View 的表現形式有不少,好比 JSON 和 HTML。開發中經常使用模板語言很常見的有 Thymeleaf、Freemarker等,那什麼是模板語言?javascript
常見的模板語言都包含如下幾個概念:數據(Data)、模板(Template)、模板引擎(Template Engine)和結果文檔(Result Documents)。html
- 數據
數據是信息的表現形式和載體,能夠是符號、文字、數字、語音、圖像、視頻等。數據和信息是不可分離的,數據是信息的表達,信息是數據的內涵。數據自己沒有意義,數據只有對實體行爲產生影響時才成爲信息。java
- 模板
模板,是一個藍圖,即一個與類型無關的類。編譯器在使用模板時,會根據模板實參對模板進行實例化,獲得一個與類型相關的類。react
- 模板引擎
模板引擎(這裏特指用於 Web 開發的模板引擎)是爲了使用戶界面與業務數據(內容)分離而產生的,它能夠生成特定格式的文檔,用於網站的模板引擎就會生成一個標準的 HTML 文檔。web
- 結果文檔
一種特定格式的文檔,好比用於網站的模板引擎就會生成一個標準的 HTML 文檔。spring
模板語言用途普遍,常見的用途以下:sql
- 頁面渲染
- 文檔生成
- 代碼生成
- 全部 「數據+模板=文本」 的應用場景
Spring Boot 推薦使用的模板語言是 Thymeleaf,那什麼是 Thymeleaf?瀏覽器
官方的解釋以下:緩存
Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
Thymeleaf 是現代的模板語言引擎,能夠獨立運行也能夠服務於 Web,主要目標是爲開發提供自然的模板,而且能在 HTML 裏面準確的顯示。springboot
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> 或者 String 都行,可是 Mono<String> 表明着我這個返回 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 等。
還有不少使用,能夠參考官方文檔。
運行工程
下面運行工程驗證下,使用 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 來實現一個總體的簡單案例。