Spring Boot + Thymeleaf + RESTful API 前后端整合完整示例

关键词:Spring Boot、Thymeleaf、RESTful API、前后端整合、用户管理


✅ 功能概述

本文将为你提供一个完整的 Spring Boot + Thymeleaf + RESTful API 的前后端整合项目,实现以下功能:

模块 功能
用户管理 查看用户列表、新增用户、删除用户
后端接口 提供 JSON 格式的 RESTful API
前端页面 使用 Thymeleaf 渲染 HTML 页面
数据持久化 使用 Spring Data JPA + H2 内存数据库

📦 一、创建 Spring Boot 项目

1. 使用idea创建项目

选择如下配置:

  • Project: Maven
  • Language: Java
  • Spring Boot Version: 3.x(如 3.3)
  • Dependencies:
    • Spring Web
    • Spring Data JPA
    • Thymeleaf
    • H2 Database (用于测试)

下载并解压后导入 IDE(如 IntelliJ IDEA 或 Eclipse)。


📁 二、项目结构概览

复制代码
springboot-thymeleaf-restful/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── demo/
│   │   │               ├── DemoApplication.java
│   │   │               ├── controller/
│   │   │               │   └── UserController.java
│   │   │               ├── model/
│   │   │               │   └── User.java
│   │   │               ├── repository/
│   │   │               │   └── UserRepository.java
│   │   │               └── service/
│   │   │                   └── UserService.java
│   │   └── resources/
│   │       ├── templates/
│   │       │   └── users.html
│   │       └── application.properties
└── pom.xml

🧱 三、添加依赖(pom.xml)

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

    <!-- Spring Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

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

    <!-- H2 Database -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- 测试依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

🗃️ 四、数据模型与数据库操作

1. 实体类 User.java

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

import jakarta.persistence.*;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    public User() {}

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // Getter & Setter
}

2. Repository 接口 UserRepository.java

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

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

3. 服务层 UserService.java

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

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }

    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }
}

🎛️ 五、控制器 UserController.java

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

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 展示用户页面
    @GetMapping("")
    public String showUsers(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "users";
    }

    // 新增用户
    @PostMapping("/add")
    public String addUser(@ModelAttribute User user) {
        userService.saveUser(user);
        return "redirect:/users";
    }

    // 删除用户
    @GetMapping("/{id}/delete")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteUserById(id);
        return "redirect:/users";
    }

    // 返回 JSON 格式的所有用户(供外部调用)
    @GetMapping(path = "/api", produces = "application/json")
    @ResponseBody
    public List<User> getUsersJson() {
        return userService.getAllUsers();
    }
}

🖼️ 六、前端页面 templates/users.html

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h2>用户管理</h2>

    <!-- 表单提交 -->
    <form th:action="@{/users/add}" method="post">
        <div class="mb-3">
            <label for="name" class="form-label">姓名</label>
            <input type="text" name="name" id="name" class="form-control" required />
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">邮箱</label>
            <input type="email" name="email" id="email" class="form-control" required />
        </div>
        <button type="submit" class="btn btn-primary">添加用户</button>
    </form>

    <hr />

    <!-- 用户列表 -->
    <table class="table table-bordered mt-4">
        <thead>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="user : ${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.email}"></td>
            <td>
                <a th:href="@{/{id}/delete(id=${user.id})}" class="btn btn-danger btn-sm">删除</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>
</body>
</html>

⚙️ 七、配置文件 application.properties

properties 复制代码
# H2 数据库配置
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

# 开启 H2 控制台
spring.h2.console.enabled=true

# Thymeleaf 缓存关闭(开发阶段)
spring.thymeleaf.cache=false

▶️ 八、运行与测试

1. 启动项目

运行 DemoApplication.java 中的 main() 方法启动 Spring Boot 应用。

2. 访问页面

打开浏览器访问:

复制代码
http://localhost:8080/users

你会看到用户管理页面,可以:

  • 添加用户(提交表单)
  • 查看用户列表
  • 删除用户

3. 调用 RESTful API

访问 JSON 格式的用户列表:

复制代码
GET http://localhost:8080/users/api

返回结果类似:

json 复制代码
[
    {"id":1,"name":"张三","email":"zhangsan@example.com"}
]

✅ 总结

技术点 内容
Spring Boot 整合 Thymeleaf 快速搭建前后端一体化应用
RESTful API 设计 提供 JSON 接口供其他系统调用
MVC 架构实践 控制器、模型、视图三层清晰分工
内存数据库 H2 快速测试无需安装数据库
前后端共存 同时支持 HTML 页面和 JSON 接口
相关推荐
程序员小崔日记15 小时前
技术之外,皆是人间
后端·ruoyi·计算机温情
不懂的浪漫15 小时前
# mqtt-plus 架构解析(八):Spring Boot 自动装配,这些零件是怎么被粘合起来的
spring boot·后端·物联网·mqtt·架构
却话巴山夜雨时i15 小时前
互联网大厂Java面试场景:Spring Boot、微服务与Redis实战解析
spring boot·redis·微服务·kafka·prometheus·java面试·电商场景
开心就好202516 小时前
Flutter iOS应用混淆与安全配置详细文档指南
后端·ios
掘金者阿豪16 小时前
记一次NFS下的权限踩坑:从“Operation not permitted”到安装成功的折腾实录
后端
妙蛙种子31116 小时前
【Java设计模式 | 创建者模式】 原型模式
java·开发语言·后端·设计模式·原型模式
阿聪谈架构16 小时前
第07章(下):LangGraph 工作流进阶 —— 检查点、人工介入与多 Agent 协作
人工智能·后端
希望永不加班16 小时前
SpringBoot 配置绑定:@ConfigurationProperties
java·spring boot·后端·spring
悟空码字16 小时前
MySQL性能优化的天花板:10条你必须掌握的顶级SQL分析技巧
java·后端·mysql
indexsunny16 小时前
互联网大厂Java面试实战:Spring Boot、MyBatis与Kafka在电商场景中的应用
java·spring boot·面试·kafka·mybatis·电商·技术栈