当前位置: 首页 > news >正文

【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!

上周,实习生小王问我:

“小马哥,我想做个用户管理的小项目练手,但网上教程要么太复杂,要么跑不起来……有没有一个简单、完整、能直接跑的 demo?”

我笑了笑:“当然有!今天我就带你用 Spring Boot + Vue3(纯 HTML/JS 版),5 分钟搭一个用户管理系统——不用装 Node,不用配 Webpack,一个 HTML 文件搞定前端!

✅ 后端:Spring Boot + Spring Web + H2(内存数据库,无需 MySQL)
✅ 前端:纯 HTML + JS + Axios(零构建,双击就能开)
✅ 功能:增删改查(CRUD) + 实时刷新

🛠️ 一、准备工作(只需 1 分钟)

你需要:

  • JDK 17(或 8/11)
  • IDEA(或 VS Code)
  • 浏览器(Chrome/Firefox)

不需要:MySQL、Node.js、npm、Tomcat!


📦 二、创建 Spring Boot 项目(IDEA 操作)

步骤 1:新建项目

  1. 打开 IDEA → New Project
  2. 选择 Spring Initializr
  3. 填写:
    • Group: com.example
    • Artifact: user-manager
  4. Dependencies 添加
    • Spring Web
    • H2 Database(内存数据库,重启清空,适合练手)

💡 为什么用 H2?
不用装 MySQL!数据存在内存,启动即用,关掉就清,干净利落。

步骤 2:生成项目

点击 Next → Finish,等待 IDEA 下载依赖。

💻 三、编写后端代码(复制即用)

1. 创建 User 实体类

// src/main/java/com/example/usermanager/model/User.java
package com.example.usermanager.model;public class User {private Long id;private String name;private String email;// 构造函数public User() {}public User(Long id, String name, String email) {this.id = id;this.name = name;this.email = email;}// getter / setterpublic Long getId() { return id; }public void setId(Long id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; }public String getEmail() { return email; }public void setEmail(String email) { this.email = email; }
}

2. 创建 UserService(内存模拟数据库)

// src/main/java/com/example/usermanager/service/UserService.java
package com.example.usermanager.service;import com.example.usermanager.model.User;
import org.springframework.stereotype.Service;import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;@Service
public class UserService {private final Map<Long, User> userMap = new ConcurrentHashMap<>();private final AtomicLong idGenerator = new AtomicLong(1);public List<User> getAllUsers() {return new ArrayList<>(userMap.values());}public User getUserById(Long id) {return userMap.get(id);}public User createUser(User user) {user.setId(idGenerator.getAndIncrement());userMap.put(user.getId(), user);return user;}public User updateUser(Long id, User user) {if (userMap.containsKey(id)) {user.setId(id);userMap.put(id, user);return user;}return null;}public void deleteUser(Long id) {userMap.remove(id);}
}

3. 创建 UserController(REST API)

// src/main/java/com/example/usermanager/controller/UserController.java
package com.example.usermanager.controller;import com.example.usermanager.model.User;
import com.example.usermanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@CrossOrigin(origins = "*") // 👈 允许前端跨域访问(开发用)
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}@PostMappingpublic User createUser(@RequestBody User user) {return userService.createUser(user);}@PutMapping("/{id}")public User updateUser(@PathVariable Long id, @RequestBody User user) {return userService.updateUser(id, user);}@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userService.deleteUser(id);}
}

4. 主启动类(默认即可)

// src/main/java/com/example/usermanager/UserManagerApplication.java
package com.example.usermanager;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class UserManagerApplication {public static void main(String[] args) {SpringApplication.run(UserManagerApplication.class, args);}
}

🌐 四、编写前端页面(一个 HTML 文件搞定!)

在项目根目录新建 frontend 文件夹,创建 index.html

<!-- frontend/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>用户管理系统</title><style>body { font-family: Arial, sans-serif; margin: 40px; }table { border-collapse: collapse; width: 100%; margin-top: 20px; }th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }th { background-color: #f2f2f2; }.form-group { margin: 10px 0; }input { padding: 6px; width: 200px; }button { padding: 8px 16px; margin-right: 8px; cursor: pointer; }</style>
</head>
<body><h1>用户管理系统(Spring Boot + 纯前端)</h1><div><h3>新增/编辑用户</h3><div class="form-group"><input type="hidden" id="userId"><input type="text" id="name" placeholder="姓名"><input type="email" id="email" placeholder="邮箱"><button onclick="saveUser()">保存</button><button onclick="clearForm()">清空</button></div></div><div><h3>用户列表</h3><table id="userTable"><thead><tr><th>ID</th><th>姓名</th><th>邮箱</th><th>操作</th></tr></thead><tbody id="userList"></tbody></table></div><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>// 页面加载时获取用户列表window.onload = function() {loadUsers();};// 获取所有用户function loadUsers() {axios.get('http://localhost:8080/api/users').then(response => {const users = response.data;const tbody = document.getElementById('userList');tbody.innerHTML = '';users.forEach(user => {const row = `<tr><td>${user.id}</td><td>${user.name}</td><td>${user.email}</td><td><button onclick="editUser(${user.id})">编辑</button><button onclick="deleteUser(${user.id})" style="background:#f44336;color:white;">删除</button></td></tr>`;tbody.innerHTML += row;});}).catch(error => {alert('加载用户失败:' + error.message);});}// 保存用户(新增或更新)function saveUser() {const id = document.getElementById('userId').value;const name = document.getElementById('name').value;const email = document.getElementById('email').value;if (!name || !email) {alert('请填写姓名和邮箱!');return;}const user = { name, email };if (id) {// 更新axios.put(`http://localhost:8080/api/users/${id}`, user).then(() => {alert('更新成功!');clearForm();loadUsers();});} else {// 新增axios.post('http://localhost:8080/api/users', user).then(() => {alert('新增成功!');clearForm();loadUsers();});}}// 编辑用户function editUser(id) {axios.get(`http://localhost:8080/api/users/${id}`).then(response => {const user = response.data;document.getElementById('userId').value = user.id;document.getElementById('name').value = user.name;document.getElementById('email').value = user.email;});}// 删除用户function deleteUser(id) {if (confirm('确定删除该用户?')) {axios.delete(`http://localhost:8080/api/users/${id}`).then(() => {alert('删除成功!');loadUsers();});}}// 清空表单function clearForm() {document.getElementById('userId').value = '';document.getElementById('name').value = '';document.getElementById('email').value = '';}</script>
</body>
</html>

前端特点

  • 无需构建,双击 index.html 即可打开
  • 使用 CDN 引入 Axios,自动处理 AJAX
  • 支持增删改查 + 实时刷新

▶️ 五、运行项目(30 秒搞定)

步骤 1:启动后端

  1. 在 IDEA 中运行 UserManagerApplication.java
  2. 看到日志:
Tomcat started on port(s): 8080

步骤 2:打开前端

  1. 用浏览器打开 frontend/index.html不要用 IDEA 内置浏览器!
  2. 你会看到空白列表(因为初始无数据)

步骤 3:添加用户

  • 填写姓名、邮箱 → 点“保存”
  • 列表自动刷新,显示新用户!

🎉 恭喜!你已成功跑通一个完整的前后端分离用户管理系统!

💬 七、写在最后

这个项目虽然简单,但包含了:

  • ✅ RESTful API 设计
  • ✅ 前后端分离架构
  • ✅ 跨域处理(@CrossOrigin
  • ✅ 内存数据存储(适合练手)

你可以在此基础上:

  • 改用 MySQL 持久化数据
  • 加入登录认证
  • 用 Vue/React 重构前端

记住:所有大项目,都始于一个能跑通的“Hello World”!

http://www.dtcms.com/a/495887.html

相关文章:

  • 什么网站源码做分类信息网站好WordPress巨卡无比
  • 网站不绑定域名解析网络优化app哪个好
  • 数据结构(4)--------------- 串
  • 湖北网站建设网址上海有哪些做网站的
  • 最新vmware安装kali
  • 端口号、常见协议和套接字
  • YOLOv3 核心知识点解析
  • 企业网站建设费怎么记账最近时政热点新闻
  • 2022年ASOC SCI2区TOP,基于竞争与合作策略的金字塔粒子群算法PPSO,深度解析+性能实测,深度解析+性能实测
  • 深入理解C++中的浅拷贝与深拷贝:从类的拷贝函数开始
  • 公网站建设浙江最新通知今天
  • 免费高效的一站式解决多种文件处理需求的PC工具箱
  • ESXI主机重置带外密码
  • Mysql 使用not in进行数据筛选是需要主要的事项
  • Java基础——面向对象进阶复习知识点4
  • 残疾人信息无障碍网站建设摄影网页
  • 创业服务网网站建设方案项目书wordpress设置自定义主页
  • AI一键生成在线考试系统:从概念到实现的技术架构解析
  • win10LTSC图片打不开
  • 品牌网站建设预算宁夏建设局官方网站
  • SQL中Replace Into语句详解
  • 做汽车英文网站南京网站模板
  • 深入理解软件设计中的协议与规范:从理论到Java实践
  • 网站建设的商品编码广州软件开发培训机构有哪些
  • PostgreSQL 15二进制文件
  • 学习LCR电桥(手持和台式)
  • 做百度网站还是安居客网站装饰装修工程
  • 电商全渠道支付系统搭建:线上线下一体化API对接指南
  • 开发实战 - ego商城 - 2 公共方法封装
  • 制作网站的公司还能赚钱吗模拟手机营销网站