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

发布于:2025-07-15 ⋅ 阅读:(15) ⋅ 点赞:(0)

关键词: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)

<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

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

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

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

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

<!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

# 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

返回结果类似:

[
    {"id":1,"name":"张三","email":"zhangsan@example.com"}
]

✅ 总结

技术点 内容
Spring Boot 整合 Thymeleaf 快速搭建前后端一体化应用
RESTful API 设计 提供 JSON 接口供其他系统调用
MVC 架构实践 控制器、模型、视图三层清晰分工
内存数据库 H2 快速测试无需安装数据库
前后端共存 同时支持 HTML 页面和 JSON 接口

网站公告

今日签到

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