使用Spring Boot和Vue实现前后端分离架构

在现代Web开发中,前后端分离已成为一种流行的架构模式。前端使用Vue.js构建用户界面,而后端使用Spring Boot处理业务逻辑和数据存取。本文将逐步引导你实现一个简单的Spring Boot与Vue.js前后端分离架构,并帮助你理解每一步的执行。

主要步骤

我们将通过以下步骤完成前后端分离架构的搭建:

步骤 描述
1 创建Spring Boot项目
2 创建Vue.js项目
3 在Spring Boot中实现REST API
4 在Vue.js中使用Axios调用API
5 启用跨域访问控制
6 编译和运行项目

每一步的详细说明

步骤 1: 创建Spring Boot项目

使用Spring Initializr创建一个新的Spring Boot项目,包含以下依赖项:

  • Spring Web
  • Spring Data JPA
  • H2 Database(或你选择的数据库)

你可以通过以下命令创建一个基础项目:

curl  -d dependencies=web,data-jpa,h2 -d name=springboot-vue -d packageName=com.example.springbootvue -o springboot-vue.zip
unzip springboot-vue.zip
cd springboot-vue

步骤 2: 创建Vue.js项目

在你的工作目录下运行以下命令创建一个新的Vue.js项目:

npm install -g @vue/cli
vue create vue-client

选择“Manually select features”,并选择“Router”以及“Vuex”。

步骤 3: 在Spring Boot中实现REST API

创建一个简单的控制器,返回一个“Hello World”消息。

文件路径:src/main/java/com/example/springbootvue/controller/HelloController.java

package com.example.springbootvue.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController // 表示这是一个RESTful控制器
public class HelloController {

    @GetMapping("/api/hello") // 处理GET请求
    public String hello() {
        return "Hello World"; // 返回字符串
    }
}

步骤 4: 在Vue.js中使用Axios调用API

在Vue应用程序中,我们将使用Axios库调用后端API。

首先,在Vue项目中安装Axios。

cd vue-client
npm install axios

然后,在src/components/HelloWorld.vue中添加以下代码:

<template>
  <div>
    {{ message }}
    <button @click="fetchHello">Fetch Hello</button>
  </div>
</template>

<script>
import axios from 'axios'; // 导入Axios库

export default {
  data() {
    return {
      message: '' // 用于存储从后端获取的消息
    };
  },
  methods: {
    fetchHello() {
      axios.get('http://localhost:8080/api/hello') // 发送GET请求到后端API
        .then(response => {
          this.message = response.data; // 将返回的数据赋值给message
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
}
</script>

步骤 5: 启用跨域访问控制

为了允许Vue前端访问Spring Boot后端,我们需要在Spring Boot中配置CORS。

src/main/java/com/example/springbootvue/config/WebConfig.java中添加如下代码:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**") // 允许请求的路径
                .allowedOrigins("http://localhost:8081"); // 允许跨域的来源
    }
}

步骤 6: 编译和运行项目

首先,运行Spring Boot后端:

./mvnw spring-boot:run

然后,切换到Vue项目并启动开发服务器:

cd vue-client
npm run serve

现在,你可以在浏览器中访问http://localhost:8081,点击“Fetch Hello”按钮,你会看到页面显示“Hello World”。

旅行图

以下是基于mermaid语法的旅行图,描绘了整个实现过程中的步骤:

journey
    title Spring Boot与Vue前后端分离架构实现
    section 创建Spring Boot项目
      创建项目: 5: 波动
      添加依赖: 4: 波动
    section 创建Vue.js项目
      安装Vue CLI: 5: 波动
      创建Vue项目: 5: 波动
    section 实现REST API
      编写控制器: 4: 波动
    section 调用API
      使用Axios: 4: 波动
    section 启用跨域
      配置CORS: 5: 波动
    section 启动项目
      启动后端: 4: 波动
      启动前端: 5: 波动

结尾

至此,你已经成功搭建了一个基于Spring Boot和Vue.js的前后端分离架构。希望本文能为你提供一个清晰的指导,帮助你在实际开发中更高效地进行前后端交互。继续实践与探索,相信你会在开发之路上越走越远!