spring boot + thymeleaf整合完整例子

以下是一个完整的 Spring Boot + Thymeleaf 整合示例,包含项目结构、代码和运行说明:


1. 项目依赖配置(Maven)

在 pom.xml 中添加 Thymeleaf 依赖:

xml 复制代码
<dependencies>
    <!-- Spring Boot Web Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

    <!-- Spring Boot DevTools (可选,用于热更新) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

2. 项目结构

复制代码
src/
├── main/
│   ├── java/
│   │   └── com.example.demo/
│   │       ├── DemoApplication.java      // 启动类
│   │       └── controller/               // 控制器包
│   │           └── HelloController.java  // 示例控制器
│   └── resources/
│       ├── static/                       // 静态资源(CSS/JS)
│       ├── templates/                    // Thymeleaf 模板文件
│       │   └── hello.html               // 示例模板
│       └── application.properties        // 配置文件(可选)
└── test/
    └── ...                               // 测试代码

3. 启动类(DemoApplication.java)

java 复制代码
package com.example.demo;

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);
    }
}

4. 控制器(HelloController.java)

java 复制代码
package com.example.demo.controller;

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

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        // 向模板传递数据
        model.addAttribute("name", "Thymeleaf");
        model.addAttribute("users", new String[]{"Alice", "Bob", "Charlie"});
        return "hello"; // 对应 templates/hello.html
    }
}

5. Thymeleaf 模板(hello.html)

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="'Hello, ' + ${name} + '!'">Default Text</h1>
    
    <!-- 条件判断 -->
    <p th:if="${users.size() > 0}">Users list:</p>
    <ul>
        <!-- 遍历用户列表 -->
        <li th:each="user : ${users}" th:text="${user}"></li>
    </ul>

    <!-- 表单示例 -->
    <form action="#" th:action="@{/submit}" method="post">
        <input type="text" th:field="*{username}" placeholder="Enter name">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

6. 配置(application.properties 可选)

properties 复制代码
# Thymeleaf 配置(可选,默认配置已足够)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false # 开发时关闭缓存

7. 运行与验证

  1. 启动应用:运行 DemoApplication 的 main 方法。
  2. 访问 http://localhost:8080/hello,页面显示:
    • 标题:Hello, Thymeleaf!
    • 用户列表:Alice, Bob, Charlie
    • 表单输入框

关键点总结

功能 实现方式
模板路径 src/main/resources/templates/ 目录下的 HTML 文件,后缀为 .html 或 .xhtml
数据绑定 通过 Model 对象传递数据到模板,使用 ${variable} 语法引用变量
条件渲染 th:if, th:unless 控制元素显示
循环遍历 th:each 遍历集合数据
表单绑定 th:field 自动绑定表单字段到后端对象

扩展示例:带表单提交的控制器

java 复制代码
@Controller
public class FormController {

    @GetMapping("/form")
    public String showForm(Model model) {
        model.addAttribute("user", new User()); // 表单对象
        return "form";
    }

    @PostMapping("/submit")
    public String submitForm(@ModelAttribute User user) {
        // 处理提交数据
        return "redirect:/success";
    }
}

对应的表单模板 form.html:

html 复制代码
<form th:object="${user}" action="#" th:action="@{/submit}" method="post">
    <input type="text" th:field="*{name}" placeholder="Name">
    <input type="email" th:field="*{email}" placeholder="Email">
    <button type="submit">Submit</button>
</form>
相关推荐
豆角焖肉3 分钟前
SpringBoot+JWT 实现前后端分离登录鉴权
java·开发语言·spring boot·jwt·前后端分离·登录认证
高频因子挖掘机4 分钟前
Python 批量获取股票行情后,如何用 Pandas 统一字段、索引和数据类型?
后端·github·api
Wang's Blog11 分钟前
Java 项目部署之 Docker工具快速入门: 自定义镜像的分层结构与写时复制
java·开发语言·docker
高频因子挖掘机26 分钟前
多股票 K 线如何用 Pandas 对齐?从收益率计算到横截面分析
后端·github·api
WeiXin_DZbishe9 小时前
基于springboot宠物领养系统-计算机毕设 附源码【课程设计】94217
vue.js·spring boot·python·django·php·课程设计
架构技术专栏9 小时前
Agent 工具调用:从工具声明到执行反馈
前端·人工智能·后端
vx_bisheyuange9 小时前
基于SpringBoot的体育商品推荐系统
spring boot·毕业设计
别动我齐刘海10 小时前
C++ 工程化学习
java·linux·前端·c++·学习·机器学习·机器人
码事漫谈10 小时前
你让AI干的活,它可能只干了十分之一——而你根本看不出来
后端
Wx-bishekaifayuan10 小时前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
人工智能·spring boot·后端·python·课程设计·express·旅游