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 接口
相关推荐
颜酱6 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
大黄说说7 小时前
筑牢Web安全防线:全面解析SQL注入与XSS攻击防护
restful
小码哥_常7 小时前
Java后端定时任务抉择:@Scheduled、Quartz、XXL - Job终极对决
后端
uzong7 小时前
Skill 被广泛应用,到底什么是 Skill,今天详细介绍一下
人工智能·后端·面试
小码哥_常7 小时前
Kafka平替!SpringBoot+Redis Stream+消费组打造极致消息队列
后端
IT_陈寒9 小时前
Redis缓存击穿:3个鲜为人知的防御策略,90%开发者都忽略了!
前端·人工智能·后端
uzong9 小时前
Harness Engineering 是什么?一场新的 AI 范式已经开始
人工智能·后端·架构
唐叔在学习10 小时前
Python桌面端应用最小化托盘开发实践
后端·python·程序员
yuhaiqiang10 小时前
被 AI 忽悠后,开始怀念搜索引擎了?
前端·后端·面试
二闹11 小时前
Python文件读取三巨头你该选择哪一个?
后端·python