从零开始搭建Spring Boot+Vue前后端分离项目
在当今的Web开发领域,前后端分离架构凭借其高可维护性、高扩展性和团队协作效率高等优势,成为了主流的开发模式。本文将带领大家从零开始搭建一个基于Spring Boot和Vue的前后端分离项目,实现简单的用户信息增删改查功能,帮助你快速掌握前后端分离开发的核心流程。
一、环境准备
后端环境
1. JDK:确保本地安装JDK 1.8及以上版本,可通过 java -version 命令检查。
2. Maven:用于项目依赖管理,安装后配置好环境变量, mvn -v 检查安装情况。
3. IDE:推荐使用IntelliJ IDEA,方便进行Spring Boot项目开发。
前端环境
1. Node.js:安装Node.js,其自带npm包管理器, node -v 和 npm -v 查看版本。
2. Vue CLI:全局安装Vue CLI,通过 npm install -g @vue/cli 命令安装, vue -V 检查是否安装成功。
3. 代码编辑器:如Visual Studio Code,具备丰富的前端开发插件。
二、创建后端Spring Boot项目
1. 创建项目:打开IntelliJ IDEA,选择“Create New Project”,在左侧选择“Spring Initializr”,设置项目基本信息,如Group、Artifact、Project SDK等,依赖项勾选 Spring Web 、 Spring Data JPA 和 MySQL Driver ,点击“Next”完成项目创建。
2. 配置数据库:在 src/main/resources/application.properties 文件中添加MySQL数据库配置:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
3. 创建实体类:在 src/main/java/com/your_package_name/entity 包下创建 User 实体类:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// 省略getter和setter方法
}
4. 创建数据访问层:在 src/main/java/com/your_package_name/repository 包下创建 UserRepository 接口,继承 JpaRepository<User, Long> :
import com.your_package_name.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
5. 创建服务层:在 src/main/java/com/your_package_name/service 包下创建 UserService 接口及实现类 UserServiceImpl :
import com.your_package_name.entity.User;
import com.your_package_name.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServiceImpl {
private final UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User saveUser(User user) {
return userRepository.save(user);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public Optional<User> getUserById(Long id) {
return userRepository.findById(id);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
6. 创建控制器层:在 src/main/java/com/your_package_name/controller 包下创建 UserController :
import com.your_package_name.entity.User;
import com.your_package_name.service.UserServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserServiceImpl userService;
public UserController(UserServiceImpl userService) {
this.userService = userService;
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userService.saveUser(user);
return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
}
@GetMapping
public ResponseEntity<List<User>> getUsers() {
List<User> users = userService.getAllUsers();
return new ResponseEntity<>(users, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
Optional<User> user = userService.getUserById(id);
return user.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
Optional<User> user = userService.getUserById(id);
if (user.isPresent()) {
User updatedUser = user.get();
updatedUser.setUsername(userDetails.getUsername());
updatedUser.setPassword(userDetails.getPassword());
userService.saveUser(updatedUser);
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
三、创建前端Vue项目
1. 创建项目:打开命令行工具,进入项目存放目录,执行 vue create vue-frontend 命令,选择默认配置或自定义配置创建Vue项目。
2. 安装依赖:进入项目目录 cd vue-frontend ,执行 npm install axios 安装axios用于前后端数据交互。
3. 创建组件:在 src/components 目录下创建 UserList.vue 、 UserForm.vue 等组件。
UserList.vue:
<template>
<div>
<h2>用户列表</h2>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.username }}</td>
<td>{{ user.password }}</td>
<td>
<button @click="editUser(user.id)">编辑</button>
<button @click="deleteUser(user.id)">删除</button>
</td>
</tr>
</tbody>
</table>
<UserForm v-if="editMode" :user="editUser" @close="closeEdit" />
</div>
</template>
<script>
import axios from 'axios';
import UserForm from './UserForm.vue';
export default {
components: {
UserForm
},
data() {
return {
users: [],
editMode: false,
editUser: {}
};
},
created() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
try {
const response = await axios.get('http://localhost:8080/users');
this.users = response.data;
} catch (error) {
console.error('Error fetching users:', error);
}
},
async deleteUser(id) {
try {
await axios.delete(`http://localhost:8080/users/${id}`);
this.fetchUsers();
} catch (error) {
console.error('Error deleting user:', error);
}
},
editUser(id) {
this.editMode = true;
this.fetchUserById(id);
},
async fetchUserById(id) {
try {
const response = await axios.get(`http://localhost:8080/users/${id}`);
this.editUser = response.data;
} catch (error) {
console.error('Error fetching user:', error);
}
},
closeEdit() {
this.editMode = false;
this.editUser = {};
this.fetchUsers();
}
}
};
</script>
UserForm.vue:
<template>
<div>
<h2>{{ editUser.id? '编辑用户' : '创建用户' }}</h2>
<form @submit.prevent="saveUser">
<label>用户名:</label>
<input type="text" v-model="editUser.username" />
<label>密码:</label>
<input type="password" v-model="editUser.password" />
<button type="submit">{{ editUser.id? '保存修改' : '创建' }}</button>
<button @click="closeForm">取消</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
props: {
user: {
type: Object,
default: () => ({})
}
},
data() {
return {
editUser: {...this.user }
};
},
methods: {
async saveUser() {
try {
if (this.editUser.id) {
await axios.put(`http://localhost:8080/users/${this.editUser.id}`, this.editUser);
} else {
await axios.post('http://localhost:8080/users', this.editUser);
}
this.$emit('close');
} catch (error) {
console.error('Error saving user:', error);
}
},
closeForm() {
this.$emit('close');
}
}
};
</script>
4. 配置路由:在 src/router/index.js 中配置路由:
import Vue from 'vue';
import Router from 'vue-router';
import UserList from '../components/UserList.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'UserList',
component: UserList
}
]
});
四、项目运行与测试
1. 启动后端项目:在IntelliJ IDEA中运行Spring Boot项目的主类,默认端口为8080。
2. 启动前端项目:在命令行进入前端项目目录 vue-frontend ,执行 npm run serve ,项目会在默认端口8081启动。
3. 测试功能:打开浏览器,访问 http://localhost:8081 ,可以进行用户信息的增删改查操作,验证前后端功能是否正常。
通过以上步骤,我们成功搭建了一个Spring Boot+Vue的前后端分离项目。当然,实际项目中还需要考虑更多的细节,如安全认证、性能优化、错误处理等。希望本文能为你的前后端分离开发之旅提供有益的帮助。