天天看点

Thymeleaf模板入门(一)

Thymeleaf模板使用

1. 简介

官网:https://www.thymeleaf.org/index.html

Thymeleaf是一种基于服务端的Java模板引擎技术,具有丰富的标签语言、函数和表达式。

2. 环境准备

2.1 创建maven项目

2.2 引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.4</version>
            </plugin>
        </plugins>
    </build>
</project>
           

2.3 默认配置

启动器已经把thymeleaf视图器配置完成,模板文件位置也已经配置完成

  • 默认前缀:classpath:/templates/
  • 默认后缀:.html

在测试中,常常需要关闭页面缓存

spring:
  thymeleaf:
    cache: false
           

3. 快速开始

3.1 启动类

package top.infinxkj.thymeleaf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }
}

           

3.2 controller

package top.infinxkj.thymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class DemoController {
    @GetMapping
    public String hello(){
        return "hello";
    }
}

           

3.3 HTML

<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>
<h1>这是一个测试页面</h1>
</body>
</html>
           

注意,把html 的名称空间,改成:

xmlns:th="http://www.thymeleaf.org"

会有语法提示

3.4 测试

启动DemoApplication类,打开浏览器输入:http://localhost:8080/

Thymeleaf模板入门(一)