怎么搭建SpringBoot+Vue前后端分离

发布时间:2023-03-30 17:33:14 作者:iii
来源:亿速云 阅读:375

怎么搭建SpringBoot+Vue前后端分离

目录

  1. 引言
  2. 技术栈介绍
  3. 环境准备
  4. Spring Boot后端搭建
  5. Vue前端搭建
  6. 前后端联调
  7. 部署与上线
  8. 常见问题与解决方案
  9. 总结

引言

在现代Web开发中,前后端分离的架构模式越来越受到开发者的青睐。前后端分离不仅能够提高开发效率,还能使前后端开发人员更加专注于各自的领域。本文将详细介绍如何使用Spring Boot和Vue.js搭建一个前后端分离的项目,并涵盖从环境准备到项目部署的完整流程。

技术栈介绍

Spring Boot

Spring Boot是一个基于Spring框架的快速开发框架,它简化了Spring应用的初始搭建和开发过程。Spring Boot提供了大量的自动配置,使得开发者可以快速构建独立的、生产级别的Spring应用程序。

Vue.js

Vue.js是一个渐进式JavaScript框架,用于构建用户界面。Vue.js的核心库只关注视图层,易于与其他库或现有项目集成。Vue.js具有轻量级、高性能和易于上手的特点,非常适合构建单页面应用(SPA)。

环境准备

Java开发环境

在开始搭建Spring Boot项目之前,首先需要确保本地已经安装了Java开发环境。推荐使用JDK 8或更高版本。

  1. 下载JDK:从Oracle官网OpenJDK下载并安装JDK。
  2. 配置环境变量:将JDK的bin目录添加到系统的PATH环境变量中。
  3. 验证安装:在命令行中输入java -version,查看是否成功安装。

Node.js开发环境

Vue.js项目需要Node.js环境来运行和构建。Node.js是一个基于Chrome V8引擎的JavaScript运行时。

  1. 下载Node.js:从Node.js官网下载并安装Node.js。
  2. 验证安装:在命令行中输入node -vnpm -v,查看是否成功安装。

IDE选择

推荐使用以下IDE进行开发:

Spring Boot后端搭建

创建Spring Boot项目

  1. 使用Spring Initializr创建项目

    • 打开Spring Initializr
    • 选择项目类型为Maven Project,语言为Java,Spring Boot版本选择最新的稳定版。
    • 填写项目元数据(Group、Artifact、Name等)。
    • 添加依赖:Spring WebSpring Data JPAMySQL Driver等。
    • 点击Generate按钮下载项目压缩包。
  2. 导入项目到IDE

    • 解压下载的项目压缩包。
    • 使用IntelliJ IDEA打开项目,选择File -> Open,然后选择解压后的项目目录。

配置数据库

  1. 安装MySQL:如果本地没有安装MySQL,可以从MySQL官网下载并安装。

  2. 创建数据库:在MySQL中创建一个新的数据库,例如spring_vue_db

  3. 配置application.properties

    • src/main/resources目录下找到application.properties文件。
    • 添加以下配置:
     spring.datasource.url=jdbc:mysql://localhost:3306/spring_vue_db?useSSL=false&serverTimezone=UTC
     spring.datasource.username=root
     spring.datasource.password=yourpassword
     spring.jpa.hibernate.ddl-auto=update
     spring.jpa.show-sql=true
    

创建实体类

  1. 创建实体类:在src/main/java/com/example/demo目录下创建entity包,并在其中创建实体类User
   package com.example.demo.entity;

   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 name;
       private String email;

       // Getters and Setters
   }

创建Repository

  1. 创建Repository接口:在src/main/java/com/example/demo目录下创建repository包,并在其中创建UserRepository接口。
   package com.example.demo.repository;

   import com.example.demo.entity.User;
   import org.springframework.data.jpa.repository.JpaRepository;

   public interface UserRepository extends JpaRepository<User, Long> {
   }

创建Service

  1. 创建Service接口:在src/main/java/com/example/demo目录下创建service包,并在其中创建UserService接口。
   package com.example.demo.service;

   import com.example.demo.entity.User;

   import java.util.List;

   public interface UserService {
       List<User> getAllUsers();
       User getUserById(Long id);
       User createUser(User user);
       User updateUser(Long id, User user);
       void deleteUser(Long id);
   }
  1. 实现Service接口:在service包下创建impl包,并在其中创建UserServiceImpl类。
   package com.example.demo.service.impl;

   import com.example.demo.entity.User;
   import com.example.demo.repository.UserRepository;
   import com.example.demo.service.UserService;
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.stereotype.Service;

   import java.util.List;

   @Service
   public class UserServiceImpl implements UserService {

       @Autowired
       private UserRepository userRepository;

       @Override
       public List<User> getAllUsers() {
           return userRepository.findAll();
       }

       @Override
       public User getUserById(Long id) {
           return userRepository.findById(id).orElse(null);
       }

       @Override
       public User createUser(User user) {
           return userRepository.save(user);
       }

       @Override
       public User updateUser(Long id, User user) {
           User existingUser = userRepository.findById(id).orElse(null);
           if (existingUser != null) {
               existingUser.setName(user.getName());
               existingUser.setEmail(user.getEmail());
               return userRepository.save(existingUser);
           }
           return null;
       }

       @Override
       public void deleteUser(Long id) {
           userRepository.deleteById(id);
       }
   }

创建Controller

  1. 创建Controller类:在src/main/java/com/example/demo目录下创建controller包,并在其中创建UserController类。
   package com.example.demo.controller;

   import com.example.demo.entity.User;
   import com.example.demo.service.UserService;
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.web.bind.annotation.*;

   import java.util.List;

   @RestController
   @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);
       }
   }

配置跨域

  1. 配置跨域:在UserController类中添加@CrossOrigin注解,允许前端访问后端API。
   @CrossOrigin(origins = "http://localhost:8080")
   @RestController
   @RequestMapping("/api/users")
   public class UserController {
       // ...
   }

Vue前端搭建

创建Vue项目

  1. 使用Vue CLI创建项目

    • 在命令行中输入以下命令创建Vue项目:
     vue create spring-vue-frontend
    
    • 选择Manually select features,然后选择BabelRouterVuexLinter/Formatter等特性。
    • 选择2.x版本的Vue。
    • 选择ESLint + Prettier作为代码格式化工具。
    • 选择In dedicated config files作为配置文件存放方式。
    • 选择Save this as a preset for future projects以保存配置。
  2. 进入项目目录

   cd spring-vue-frontend
  1. 启动开发服务器
   npm run serve

安装Vue Router

  1. 安装Vue Router:在创建Vue项目时已经选择了Router,因此Vue Router已经自动安装并配置。

安装Axios

  1. 安装Axios:在命令行中输入以下命令安装Axios:
   npm install axios
  1. 配置Axios:在src目录下创建services目录,并在其中创建api.js文件。
   import axios from 'axios';

   const apiClient = axios.create({
       baseURL: 'http://localhost:8080/api',
       withCredentials: false,
       headers: {
           Accept: 'application/json',
           'Content-Type': 'application/json'
       }
   });

   export default {
       getUsers() {
           return apiClient.get('/users');
       },
       getUser(id) {
           return apiClient.get('/users/' + id);
       },
       createUser(user) {
           return apiClient.post('/users', user);
       },
       updateUser(id, user) {
           return apiClient.put('/users/' + id, user);
       },
       deleteUser(id) {
           return apiClient.delete('/users/' + id);
       }
   };

创建组件

  1. 创建UserList组件:在src/components目录下创建UserList.vue文件。
   <template>
       <div>
           <h1>User List</h1>
           <ul>
               <li v-for="user in users" :key="user.id">
                   {{ user.name }} - {{ user.email }}
               </li>
           </ul>
       </div>
   </template>

   <script>
   import api from '@/services/api';

   export default {
       data() {
           return {
               users: []
           };
       },
       created() {
           this.fetchUsers();
       },
       methods: {
           async fetchUsers() {
               try {
                   const response = await api.getUsers();
                   this.users = response.data;
               } catch (error) {
                   console.error(error);
               }
           }
       }
   };
   </script>
  1. 创建UserForm组件:在src/components目录下创建UserForm.vue文件。
   <template>
       <div>
           <h1>{{ isEdit ? 'Edit User' : 'Create User' }}</h1>
           <form @submit.prevent="submitForm">
               <div>
                   <label for="name">Name:</label>
                   <input type="text" id="name" v-model="user.name" required>
               </div>
               <div>
                   <label for="email">Email:</label>
                   <input type="email" id="email" v-model="user.email" required>
               </div>
               <button type="submit">{{ isEdit ? 'Update' : 'Create' }}</button>
           </form>
       </div>
   </template>

   <script>
   import api from '@/services/api';

   export default {
       props: {
           userId: {
               type: String,
               default: null
           }
       },
       data() {
           return {
               user: {
                   name: '',
                   email: ''
               },
               isEdit: false
           };
       },
       created() {
           if (this.userId) {
               this.isEdit = true;
               this.fetchUser();
           }
       },
       methods: {
           async fetchUser() {
               try {
                   const response = await api.getUser(this.userId);
                   this.user = response.data;
               } catch (error) {
                   console.error(error);
               }
           },
           async submitForm() {
               try {
                   if (this.isEdit) {
                       await api.updateUser(this.userId, this.user);
                   } else {
                       await api.createUser(this.user);
                   }
                   this.$router.push('/users');
               } catch (error) {
                   console.error(error);
               }
           }
       }
   };
   </script>

配置路由

  1. 配置路由:在src/router/index.js文件中配置路由。
   import Vue from 'vue';
   import VueRouter from 'vue-router';
   import UserList from '@/components/UserList.vue';
   import UserForm from '@/components/UserForm.vue';

   Vue.use(VueRouter);

   const routes = [
       {
           path: '/users',
           name: 'UserList',
           component: UserList
       },
       {
           path: '/users/create',
           name: 'UserCreate',
           component: UserForm
       },
       {
           path: '/users/edit/:id',
           name: 'UserEdit',
           component: UserForm,
           props: true
       }
   ];

   const router = new VueRouter({
       mode: 'history',
       routes
   });

   export default router;

调用后端API

  1. 在组件中调用API:在UserListUserForm组件中已经通过api.js调用了后端API。

前后端联调

启动后端服务

  1. 启动Spring Boot应用:在IntelliJ IDEA中右键点击DemoApplication类,选择Run 'DemoApplication'

启动前端服务

  1. 启动Vue开发服务器:在命令行中输入以下命令启动Vue开发服务器:
   npm run serve

调试与测试

  1. 访问前端页面:在浏览器中访问http://localhost:8081(Vue开发服务器默认端口为8081)。
  2. 测试API调用:在前端页面中操作,查看后端API是否被正确调用,数据是否正常显示。

部署与上线

后端部署

  1. 打包Spring Boot应用:在命令行中输入以下命令打包Spring Boot应用:
   mvn clean package
  1. 部署到服务器:将生成的target/demo-0.0.1-SNAPSHOT.jar文件上传到服务器,并使用以下命令启动应用:
   java -jar demo-0.0.1-SNAPSHOT.jar

前端部署

  1. 打包Vue应用:在命令行中输入以下命令打包Vue应用:
   npm run build
  1. 部署到服务器:将生成的dist目录上传到服务器,并配置Nginx指向该目录。

Nginx配置

  1. 安装Nginx:在服务器上安装Nginx。
   sudo apt-get install nginx
  1. 配置Nginx:编辑/etc/nginx/sites-available/default文件,添加以下配置:
   server {
       listen 80;
       server_name yourdomain.com;

       location / {
           root /path/to/your/dist;
           try_files $uri $uri/ /index.html;
       }

       location /api {
           proxy_pass http://localhost:8080;
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header X-Forwarded-Proto $scheme;
       }
   }
  1. 重启Nginx:在命令行中输入以下命令重启Nginx:
   sudo systemctl restart nginx

常见问题与解决方案

  1. 跨域问题:确保后端配置了跨域支持,或者通过Nginx代理解决跨域问题。
  2. 数据库连接问题:检查application.properties中的数据库配置是否正确,确保数据库服务已启动。
  3. 前端路由问题:确保Vue Router配置了history模式,并在Nginx中配置了try_files

总结

通过本文的详细介绍,您已经学会了如何使用Spring Boot和Vue.js搭建一个前后端分离的项目。从环境准备到项目部署,本文涵盖了完整的开发流程。希望本文能够帮助您在实际项目中快速上手前后端分离的开发模式。

推荐阅读:
  1. SpringBoot如何集成Apollo配置中心
  2. springboot + rabbitmq 做智能家居,我也没想到会这么简单

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot vue

上一篇:MySQL事务与并发控制的知识点有哪些

下一篇:怎么使用Android Flutter实现创意时钟

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》