Thymeleaf - 与SpringBoot整合入门

【1】是什么

官网地址 : https://www.thymeleaf.org/

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就能自动渲染。


【4】页面使用Thymeleaf语法

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

示例如下:

<html lang="en" xmlns:th="http://www.thymeleaf.org">

猜你喜欢

转载自blog.csdn.net/j080624/article/details/80682172