springboot如何集成thymeleaf

发布于:2025-04-10 ⋅ 阅读:(39) ⋅ 点赞:(0)

添加Pom依赖

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

 

配置Thymeleaf参数

application.propertiesapplication.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地址


网站公告

今日签到

点亮在社区的每一天
去签到