Spring Boot整合 Thymeleaf 模板引擎

什麼是Thymeleaf

Thymeleaf是一款用於渲染XML、XHTML、HTML5內容的模板引擎。相似Velocity,FreeMaker模板引擎,它也能夠輕易的與Spring MVC等Web框架進行集成做爲Web應用的模板引擎。css

Thymeleaf也是Spring Boot首要支持的模板引擎,而且在最新的Spring Boot版本中已經再也不支持Velocity了。html

官網:http://www.thymeleaf.org/jquery

引入依賴

須要引入Spring Boot的Thymeleaf啓動器依賴。web

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

引入該依賴後會自動引入web依賴,不須要再單獨引入web依賴。spring

自動配置說明

下面是Thymeleaf的自動配置相關類。微信

Thymeleaf的自動配置類:mvc

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfigurationapp

Thymeleaf的自動配置參數類:框架

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafPropertiesspring-boot

查看參數源碼:

private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");

private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");

public static final String DEFAULT_PREFIX = "classpath:/templates/";

public static final String DEFAULT_SUFFIX = ".html";

默認的編碼是:UTF-8

默認的類型是:text/html

默認的模板文件目錄是:classpath:/templates/

默認的模板文件後綴是:.html

這些參數均可以經過在application配置文件中指定spring.thymeleaf.xx進行更改,更多可參考該參數類。

實戰

知道了自動配置的原理,因此咱們能夠知道怎麼作了。

1、在resources目錄下建立templates目錄。

2、在templates目錄下建立.html模板文件。

3、使用模板:

一、模板文件頭部使用<html xmlns:th="http://www.thymeleaf.org">定義。

二、html標籤上使用th:開頭標識做爲前綴。

三、經過@{}引入web靜態文件。

<link rel="stylesheet" th:href="@{/css/jquery.min.css}"/>

四、訪問數據

訪問springmvc中的model數據:${user.name},訪問更多不一樣對象的數據請點擊參考官方定義。

推薦:Spring Boot & Cloud 最強技術教程

掃描關注咱們的微信公衆號,乾貨天天更新。

image

相關文章
相關標籤/搜索