上周,实习生小王问我:
"小马哥,我想做个用户管理的小项目练手,但网上教程要么太复杂,要么跑不起来......有没有一个简单、完整、能直接跑的 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:新建项目
- 打开 IDEA → New Project
- 选择 Spring Initializr
- 填写:
- Group:
com.example
- Artifact:
user-manager
- Group:
- Dependencies 添加 :
- Spring Web
- H2 Database(内存数据库,重启清空,适合练手)
💡 为什么用 H2?
不用装 MySQL!数据存在内存,启动即用,关掉就清,干净利落。
步骤 2:生成项目
点击 Next → Finish,等待 IDEA 下载依赖。
💻 三、编写后端代码(复制即用)
1. 创建 User 实体类
java
// 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 / setter
public 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(内存模拟数据库)
java
// 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)
java
// 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 {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping
public 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. 主启动类(默认即可)
java
// 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
:
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:启动后端
- 在 IDEA 中运行
UserManagerApplication.java
- 看到日志:
html
Tomcat started on port(s): 8080
步骤 2:打开前端
- 用浏览器打开
frontend/index.html
(不要用 IDEA 内置浏览器!) - 你会看到空白列表(因为初始无数据)
步骤 3:添加用户
- 填写姓名、邮箱 → 点"保存"
- 列表自动刷新,显示新用户!
🎉 恭喜!你已成功跑通一个完整的前后端分离用户管理系统!
💬 七、写在最后
这个项目虽然简单,但包含了:
- ✅ RESTful API 设计
- ✅ 前后端分离架构
- ✅ 跨域处理(
@CrossOrigin
) - ✅ 内存数据存储(适合练手)
你可以在此基础上:
- 改用 MySQL 持久化数据
- 加入登录认证
- 用 Vue/React 重构前端
记住:所有大项目,都始于一个能跑通的"Hello World"!