添加Pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置Thymeleaf参数
在application.properties
或application.yml
中配置模板引擎参数(开发环境建议关闭缓存):
spring:
application:
name: springDemo
thymeleaf:
suffix: .html
cache: false # 开发环境禁用缓存
encoding: UTF-8
mode: HTML5
servlet:
content-type: text/html
创建Thymeleaf模板文件
在src/main/resources/templates
目录下新建HTML文件(如home.html
),需声明Thymeleaf命名空间:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text=" ${title}">默认标题</title>
</head>
<body>
<h1 th:text=" ${message}">默认消息</h1>
</body>
</html>
编写Controller
package org.example.springdemo.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/index")
public String index(Model model) {
model.addAttribute("title", "Spring Boot + Thymeleaf 示例");
model.addAttribute("message", "欢迎访问动态页面!");
return "home"; // 返回模板文件名(无需后缀)
}
}
使用@Controller
注解类,通过Model
传递数据到模板
注意:避免使用@RestController
,否则会直接返回字符串而非渲染模板。
这里只是给个例子快速上手,具体场景的复杂用法要学会查阅官方文档
Thymeleaf thymeleaf官网
https://github.com/thymeleaf/thymeleaf thymeleaf github地址