Spring Boot(后端)与 Vue(前端)的交流主要通过 HTTP 协议 实现,具体来说是后端提供 RESTful API 接口,前端通过 Axios 等工具发送请求并处理响应。以下是详细的实现方式和配置步骤:
一、核心通信方式
- 后端(Spring Boot):
提供 API 接口(GET/POST/PUT/DELETE 等),返回 JSON 格式的数据。 - 前端(Vue):
使用 Axios 发送 HTTP 请求调用后端接口,接收 JSON 数据后渲染到页面。 - 跨域处理:
由于前后端通常运行在不同端口(如后端 8080,前端 8081),需解决跨域问题(CORS)。
二、后端(Spring Boot)配置
1. 引入 Web 依赖
在 pom.xml
中添加 Spring Web 依赖,用于开发 API 接口:
<dependencies>
<!-- Spring Web 依赖(提供 RESTful API 支持) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 可选:Lombok 简化实体类代码 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2. 解决跨域问题
Spring Boot 中通过 @CrossOrigin 注解 或 全局 CORS 配置 允许前端跨域请求。
方式一:全局配置(推荐)
创建配置类,允许所有域名 / 方法的跨域请求:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
// 1. 配置跨域信息
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*"); // 允许所有域名(生产环境需指定具体域名)
config.setAllowCredentials(true); // 允许携带 Cookie
config.addAllowedMethod("*"); // 允许所有 HTTP 方法(GET/POST 等)
config.addAllowedHeader("*"); // 允许所有请求头
// 2. 配置路径映射(所有接口都允许跨域)
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
方式二:局部注解(针对单个接口 / 控制器)
在控制器或方法上添加 @CrossOrigin
:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://localhost:8081") // 允许前端 8081 端口访问
public class UserController {
// ...
}
3. 开发 API 接口
创建控制器类,提供数据接口(返回 JSON 格式):
import lombok.Data;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
// 模拟用户数据
private static final List<User> users = new ArrayList<>();
static {
users.add(new User(1L, "张三", 20));
users.add(new User(2L, "李四", 22));
}
// GET 请求:查询所有用户
@GetMapping
public List<User> getUsers() {
return users;
}
// GET 请求:根据 ID 查询用户
@GetMapping("/{id}")
public User getUserUserById(@PathVariable Long id) {
return users.stream()
.filter(user -> user.getId().equals(id))
.findFirst()
.orElseThrow(() -> new RuntimeException("用户不存在"));
}
// POST 请求:新增用户
@PostMapping
public User addUser(@RequestBody User user) {
users.add(user);
return user;
}
// 实体类(使用 Lombok 的 @Data 简化 getter/setter)
@Data
public static class User {
private Long id;
private String name;
private Integer age;
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
}
}
三、前端(Vue)配置
1. 安装 Axios
Axios 是 Vue 中常用的 HTTP 客户端,用于发送请求:
# 创建 Vue 项目(若未创建)
vue create vue-demo
# 进入项目目录,安装 Axios
cd vue-demo
npm install axios --save
2. 配置 Axios 全局实例
在 src/utils/request.js
中创建 Axios 实例,统一配置基础路径和拦截器:
import axios from 'axios';
// 创建 Axios 实例
const request = axios.create({
baseURL: 'http://localhost:8080', // 后端接口基础路径
timeout: 5000 // 超时时间
});
// 请求拦截器(可选,如添加 token)
request.interceptors.request.use(
config => {
// 可在此请求头添加 token(如身份认证)
// config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截器(可选,统一处理错误)
request.interceptors.response.use(
response => {
return response.data; // 直接返回响应体中的 data
},
error => {
console.error('请求失败:', error);
return Promise.reject(error);
}
);
export default request;
3. 调用后端接口
在 Vue 组件中使用配置好的 Axios 实例调用后端 API:
示例组件(src/views/UserView.vue):
<template>
<div class="user-container">
<h2>用户列表</h2>
<ul>
<li v-for="user in users" :key="user.id">
{{ user.id }} - {{ user.name }} ({{ user.age }}岁)
</li>
</ul>
<h3>新增用户</h3>
<input v-model="newUser.name" placeholder="姓名" />
<input v-model="newUser.age" type="number" placeholder="年龄" />
<button @click="addUser">添加</button>
</div>
</template>
<script>
import request from '@/utils/request'; // 导入 Axios 实例
export default {
data() {
return {
users: [],
newUser: { name: '', age: 0 }
};
},
created() {
// 页面加载时查询所有用户
this.getUsers();
},
methods: {
// 调用后端 GET 接口
async getUsers() {
try {
this.users = await request.get('/api/users');
} catch (error) {
alert('查询失败');
}
},
// 调用后端 POST 接口
async addUser() {
try {
const newUser = {
id: Date.now(), // 简单生成唯一 ID
name: this.newUser.name,
age: this.newUser.age
};
await request.post('/api/users', newUser);
this.getUsers(); // 新增后刷新列表
this.newUser = { name: '', age: 0 }; // 清空输入
} catch (error) {
alert('新增失败');
}
}
}
};
</script>
4. 配置 Vue 路由(可选)
若需要多页面跳转,在 src/router/index.js
中配置路由:
import { createRouter, createWebHistory } from 'vue-router';
import UserView from '../views/UserView.vue';
const routes = [
{
path: '/users',
name: 'User',
component: UserView
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
四、运行与测试
- 启动后端:运行 Spring Boot 主类,默认端口
8080
。 - 启动前端:执行
npm run serve
,默认端口8080
(若冲突可在vue.config.js
中修改)。 - 访问测试:打开
http://localhost:8081/users
,即可看到前端页面通过 API 获取并展示后端数据,点击 “添加” 按钮可新增用户。
五、进阶场景
身份认证:
后端通过 JWT 生成 token,前端登录后存储 token 到 localStorage,每次请求通过 Axios 拦截器添加到请求头(Authorization: Bearer token
)。WebSocket 实时通信:
对于即时聊天、实时数据更新等场景,可使用 WebSocket(Spring Boot 集成 WebSocket,Vue 用vue-native-websocket
插件)。接口文档:
后端集成 Swagger(SpringDoc)自动生成 API 文档,方便前后端协作:<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.1.0</version> </dependency>
访问
http://localhost:8080/swagger-ui.html
查看接口文档。
通过以上步骤,Spring Boot 与 Vue 可实现高效通信,后端专注于数据处理和业务逻辑,前端专注于用户界面和交互,实现前后端分离架构。