Spring Boot整合Thymeleaf模板引擎

简介: 什么是ThymeleafThymeleaf是一款用于渲染XML、XHTML、HTML5内容的模板引擎。类似Velocity,FreeMaker模板引擎,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。

什么是Thymeleaf

Thymeleaf是一款用于渲染XML、XHTML、HTML5内容的模板引擎。类似Velocity,FreeMaker模板引擎,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。

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

官网:http://www.thymeleaf.org/

引入依赖

需要引入Spring Boot的Thymeleaf启动器依赖。

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

引入该依赖后会自动引入web依赖,不需要再单独引入web依赖。

自动配置说明

下面是Thymeleaf的自动配置相关类。

Thymeleaf的自动配置类:

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration

Thymeleaf的自动配置参数类:

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties

查看参数源码:

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进行更改,更多可参考该参数类。

实战

知道了自动配置的原理,所以我们可以知道怎么做了。

一、在resources目录下创建templates目录。

二、在templates目录下创建.html模板文件。

三、使用模板:

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

2、html标签上使用th:开头标识作为前缀。

3、通过@{}引入web静态文件。

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

4、访问数据

访问springmvc中的model数据:${user.name},访问更多不同对象的数据请点击参考官方定义。

推荐:Spring Boot & Cloud 最强技术教程

扫描关注我们的微信公众号,干货每天更新。

image
相关文章
|
26天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
40 0
|
3月前
|
前端开发 Java 开发者
Spring Boot 3 集成 Thymeleaf
Thymeleaf是一款用于Web和独立环境的现代化服务器端Java模板引擎。它能够处理HTML、XML、JavaScript、CSS甚至纯文本。Thymeleaf的语法简单易懂,它允许开发者在模板中嵌入表达式,以便动态地渲染数据。
77 1
Spring Boot 3 集成 Thymeleaf
|
5天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
11 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
7天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
29 0
【Spring系列】Sping VS Sping Boot区别与联系
|
2月前
|
XML 监控 druid
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
|
2月前
|
前端开发 JavaScript Java
防止spring把静态资源识别thymeleaf模板
防止spring把静态资源识别thymeleaf模板
11 0
|
3月前
|
Java
Springboot视图解析与模板引擎~
Springboot视图解析与模板引擎~
|
3月前
|
安全 前端开发 Java
Spring Boot+Mybatis+Thymeleaf实现宠物医院管理系统
Spring Boot+Mybatis+Thymeleaf实现宠物医院管理系统
|
3月前
|
Java
springboot项目打包瘦身
springboot项目打包瘦身
|
4月前
|
前端开发 Java Maven
spring boot 整合前端thymeleaf
spring boot 整合前端thymeleaf
26 0