Thymeleaf - 与SpringBoot整合入门

简介: Thymeleaf - 与SpringBoot整合入门

【1】是什么

Thymeleaf是一个用于Web和独立环境的现代服务器端Java模板引擎。SpringBoot推荐使用Thymeleaf。


Thymeleaf is a modern server-side Java template engine for both web and standalone environments.


Thymeleaf’s main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.


With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.

【2】SpringBoot中使用Thymeleaf

对SpringBoot来说,没有什么是一个starter解决不了的,官网示例:


在pom文件中添加依赖:

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

默认版本是2.1.6,这是比较低的,如下图:


修改版本:

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
    <!-- thymeleaf2   layout1-->
    <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>


【3】Thymeleaf使用配置规则

ThymeleafProperties 类如下:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class 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";
  /**
   * Check that the template exists before rendering it (Thymeleaf 3+).
   */
  private boolean checkTemplate = true;
  /**
   * Check that the templates location exists.
   */
  private boolean checkTemplateLocation = true;


即只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染。

另外,记得开发时在application.yml文件中设置thymeleaf缓存为false:

spring: 
  thymeleaf:
      cache: false


【4】页面使用Thymeleaf语法

HTML页面如果想使用Thymeleaf语法,则必须引入Thymeleaf命名空间。

示例如下:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
目录
相关文章
|
21天前
|
XML 前端开发 Java
Springboot整合freemarker
Springboot整合freemarker
|
21天前
|
XML JavaScript 前端开发
SpringBoot整合Freemarker使用
SpringBoot整合Freemarker使用
27 0
|
缓存 Java
springboot整合thymeleaf
springboot整合thymeleaf
185 0
|
10月前
|
移动开发 缓存 前端开发
SpringBoot整合thymeleaf
SpringBoot整合thymeleaf
|
前端开发 JavaScript IDE
SpringBoot & Thymeleaf项目实战
SpringBoot & Thymeleaf项目实战
|
缓存 编解码 移动开发
SpringBoot 整合 Thymeleaf|学习笔记
快速学习 SpringBoot 整合 Thymeleaf
154 0
SpringBoot 整合 Thymeleaf|学习笔记
|
缓存 Java 数据库
SpringBoot 整合 Freemarker|学习笔记
快速学习 SpringBoot 整合 Freemarker
152 0
SpringBoot 整合 Freemarker|学习笔记
|
XML 移动开发 前端开发
Springboot整合Thymeleaf
Springboot整合Thymeleaf
140 0

热门文章

最新文章