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

相关文章
相关标签/搜索