SpringBoot入門系列(四)整合模板引擎Thymeleaf

前面介紹了Spring Boot的優勢,而後介紹瞭如何快速建立Spring Boot 項目。不清楚的朋友能夠看看以前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.htmlhtml

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

 這個系列課程的完整源碼,也會提供給你們。你們關注個人微信公衆號(架構師精進),回覆:springboot源碼 獲取這個系列課程的完整源碼。或者點此連接直接下載完整源碼java

 

Thymeleaf 簡介

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

Thymeleaf 做爲新一代 Java 模板引擎,它的功能與 Velocity、FreeMarker 等傳統 Java 模板引擎比較相似,可是Thymeleaf  模板後綴爲 .html,能夠直接被瀏覽器打開,所以,開發時很是方便。redis

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

事實上, Thymeleaf 除了展現基本的 HTML ,進行頁面渲染以外,也能夠做爲一個 HTML 片斷進行渲染,例如咱們在作郵件發送時,可使用 Thymeleaf 做爲郵件發送模板。後端

 

整合

新項目整合 Thymeleaf 很是容易,只須要建立項目時勾上 Thymeleaf 便可,這裏就不說了。瀏覽器

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

一、在pom.xml 增長依賴以下springboot

        <!-- 引入 redis 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.5.7.RELEASE</version>
        </dependency>

二、application.properties 文件增長Thymeleaf 相關配置

############################################################
#
# 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
spring.thymeleaf.prefix 指定模板頁面的路徑

三、增長前臺頁面

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

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello Spring Boot~~~~~~~</h1>
</body>
</html>

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

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

四、建立 Controller

接下來咱們就能夠建立 Controller 了,實際上引入 Thymeleaf 依賴以後,咱們能夠不作任何配置。新建的ThymeleafController以下:

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";
    }
}

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

五、運行效果

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

 

總結

主要向你們簡單介紹了 Spring Boot 整合 Thymeleaf,仍是比較簡單的。下一篇文章會給你們詳細介紹Thymeleaf的經常使用標籤和用法。你們也能夠閱讀 Thymeleaf 官方文檔學習 Thymeleaf 的更多用法。

這個系列課程的完整源碼,也會提供給你們。你們關注個人微信公衆號(架構師精進),回覆:springboot源碼 獲取這個系列課程的完整源碼。

相關文章
相關標籤/搜索