Spring Boot 如何快熟整合Thymeleaf模板引擎

前面介紹了Spring Boot的優點,然後介紹瞭如何快速創建Spring Boot 項目。不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html。

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

Thymeleaf 簡介

Spring Boot 2主要支持頁面模板是 Thymeleaf 和 Freemarker ,當然,作為 Java 最最基本的頁面模板 Jsp ,Spring Boot 也是支持的,只是使用比較麻煩。

Thymeleaf 作為新一代 Java 模板引擎,它的功能與 Velocity、FreeMarker 等傳統 Java 模板引擎比較類似,但是Thymeleaf 模板後綴為 .html,可以直接被瀏覽器打開,因此,開發時非常方便。

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

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

整合

新項目整合 Thymeleaf 非常容易,只需要創建項目時勾上 Thymeleaf 即可,這裡就不說了。

下面說說怎麼在現有的項目中手動整合Thymeleaf:

1、在pom.xml 增加依賴如下

<code>        
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-data-redis/<artifactid>
<version>1.5.7.RELEASE/<version>
/<dependency>/<code>

2、application.properties 文件增加Thymeleaf 相關配置

<code>############################################################
#
# thymeleaf 模板
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
# 關閉緩存
spring.thymeleaf.cache=false/<code>
Spring Boot 如何快熟整合Thymeleaf模板引擎

<code>spring.thymeleaf.prefix 指定模板頁面的路徑/<code>

3、增加前臺頁面

在resource\\templates\\thymeleaf 目錄下增加index.html 頁面

<code>



<title>


Thymeleaf模板引擎

hello Spring Boot~~~~~~~



/<code>

th:text 就是Thymeleaf的標籤,用於處理標籤體的文本內容。

其他更對的標籤及用法,我會在下一篇文章中介紹。

4、創建 Controller

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

<code>package com.weiz.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.weiz.pojo.User;

@Controller
@RequestMapping("th")
public class ThymeleafController {

@RequestMapping("/index")
public String index(ModelMap map) {
map.addAttribute("name", "thymeleaf-index");
return "thymeleaf/index";
}
}/<code>
Spring Boot 如何快熟整合Thymeleaf模板引擎

在ThymeleafController 中返回邏輯視圖名,邏輯視圖名為 index ,意思我們需要在 resources/templates/thymeleaf 目錄下提供一個名為 index.html 的 Thymeleaf 模板文件。

5、運行效果

在瀏覽器中輸入:http://localhost:8080/th/index 查看頁面返回結果。

Spring Boot 如何快熟整合Thymeleaf模板引擎

總結

主要向大家簡單介紹了 Spring Boot 整合 Thymeleaf,還是比較簡單的。下一篇文章會給大家詳細介紹Thymeleaf的常用標籤和用法。大家也可以閱讀 Thymeleaf 官方文檔學習 Thymeleaf 的更多用法。


分享到:


相關文章: