🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
在这里插入图片描述

从零到精通:SpringBoot + Vue 前后端分离项目实战

一、引言

在当今的软件开发领域,前后端分离的开发模式已经成为主流。Spring Boot 作为 Java 后端开发的利器,以其简洁的配置和强大的功能,受到了广大开发者的喜爱。而 Vue.js 作为前端渐进式框架,具有轻量级、易上手等特点,能够快速构建用户界面。本文将带领大家从零开始,逐步完成一个 Spring Boot + Vue 前后端分离的项目,帮助大家掌握这一技术栈的实战应用。

二、环境搭建

2.1 后端环境搭建

2.1.1 JDK 安装

首先,我们需要安装 Java 开发工具包(JDK)。建议使用 JDK 8 及以上版本,这里以 JDK 11 为例。从 Oracle 官网或 OpenJDK 官网下载适合你操作系统的 JDK 安装包,然后按照安装向导进行安装。安装完成后,配置环境变量 JAVA_HOMEPATHCLASSPATH

2.1.2 Maven 安装

Maven 是一个强大的项目管理工具,用于管理项目的依赖和构建。从 Maven 官网下载 Maven 压缩包,解压到指定目录。配置环境变量 MAVEN_HOME,并将 %MAVEN_HOME%\bin 添加到 PATH 环境变量中。

2.1.3 Spring Boot 项目创建

使用 Spring Initializr(https://start.spring.io/)来创建一个新的 Spring Boot 项目。选择所需的依赖,如 Spring Web、Spring Data JPA、MySQL Driver 等,然后下载项目压缩包并解压到本地。

2.2 前端环境搭建

2.2.1 Node.js 安装

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,用于运行前端项目。从 Node.js 官网下载适合你操作系统的安装包,安装完成后,打开命令行工具,输入 node -vnpm -v 验证安装是否成功。

2.2.2 Vue CLI 安装

Vue CLI 是一个基于 Vue.js 进行快速项目搭建的工具。在命令行中输入以下命令进行安装:

npm install -g @vue/cli
2.2.3 Vue 项目创建

使用 Vue CLI 创建一个新的 Vue 项目。在命令行中输入以下命令:

vue create front-end-project

按照提示选择所需的配置,然后等待项目创建完成。

三、后端开发

3.1 数据库设计与配置

3.1.1 数据库设计

假设我们要开发一个简单的博客系统,需要设计用户表(users)和文章表(articles)。以下是数据库表结构的 SQL 语句:

-- 创建用户表
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
);

-- 创建文章表
CREATE TABLE articles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    user_id INT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
3.1.2 数据库配置

在 Spring Boot 项目的 application.propertiesapplication.yml 文件中配置数据库连接信息:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/blog_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

3.2 实体类与数据访问层

3.2.1 实体类创建

创建 UserArticle 实体类,使用 JPA 注解来映射数据库表:

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 方法
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;

    @ManyToOne
    private User user;

    // 省略 getter 和 setter 方法
}
3.2.2 数据访问层接口

创建 UserRepositoryArticleRepository 接口,继承 JpaRepository 来实现基本的数据库操作:

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
}
import org.springframework.data.jpa.repository.JpaRepository;

public interface ArticleRepository extends JpaRepository<Article, Long> {
}

3.3 服务层与控制器

3.3.1 服务层实现

创建 UserServiceArticleService 服务类,实现具体的业务逻辑:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {
    @Autowired
    private ArticleRepository articleRepository;

    public List<Article> getAllArticles() {
        return articleRepository.findAll();
    }

    public Article saveArticle(Article article) {
        return articleRepository.save(article);
    }
}
3.3.2 控制器实现

创建 UserControllerArticleController 控制器类,处理 HTTP 请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{username}")
    public User getUserByUsername(@PathVariable String username) {
        return userService.findByUsername(username);
    }

    @PostMapping
    public User saveUser(@RequestBody User user) {
        return userService.saveUser(user);
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/articles")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @GetMapping
    public List<Article> getAllArticles() {
        return articleService.getAllArticles();
    }

    @PostMapping
    public Article saveArticle(@RequestBody Article article) {
        return articleService.saveArticle(article);
    }
}

四、前端开发

4.1 项目结构与路由配置

4.1.1 项目结构

Vue 项目的基本结构如下:

front-end-project
├── public
│   └── index.html
├── src
│   ├── assets
│   ├── components
│   ├── views
│   ├── App.vue
│   ├── main.js
│   └── router.js
└── package.json
4.1.2 路由配置

router.js 文件中配置路由:

import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        name: 'Home',
        component: HomeView
    }
];

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
});

export default router;

4.2 组件开发

4.2.1 创建组件

components 目录下创建 ArticleList.vue 组件,用于显示文章列表:

<template>
    <div>
        <h1>文章列表</h1>
        <ul>
            <li v-for="article in articles" :key="article.id">{{ article.title }}</li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            articles: []
        };
    },
    mounted() {
        this.fetchArticles();
    },
    methods: {
        fetchArticles() {
            // 调用后端接口获取文章列表
            fetch('/api/articles')
              .then(response => response.json())
              .then(data => {
                    this.articles = data;
                });
        }
    }
};
</script>
4.2.2 使用组件

HomeView.vue 中使用 ArticleList 组件:

<template>
    <div>
        <ArticleList />
    </div>
</template>

<script>
import ArticleList from '../components/ArticleList.vue';

export default {
    components: {
        ArticleList
    }
};
</script>

4.3 与后端交互

4.3.1 跨域问题解决

由于前后端项目运行在不同的端口,会存在跨域问题。在 Spring Boot 项目中添加跨域配置:

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() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
4.3.2 数据交互

在 Vue 组件中使用 fetchaxios 等工具与后端进行数据交互。例如,在 ArticleList.vue 中使用 fetch 获取文章列表:

fetch('/api/articles')
  .then(response => response.json())
  .then(data => {
        this.articles = data;
    });

五、项目部署

5.1 后端部署

5.1.1 打包项目

在 Spring Boot 项目根目录下,使用 Maven 进行打包:

mvn clean package
5.1.2 部署到服务器

将生成的 jar 文件上传到服务器,使用以下命令启动项目:

java -jar your-project.jar

5.2 前端部署

5.2.1 打包项目

在 Vue 项目根目录下,使用以下命令进行打包:

npm run build
5.2.2 部署到服务器

将打包生成的 dist 目录下的文件上传到服务器的静态资源目录,如 Nginx 的 html 目录。

六、总结

通过本文的学习,我们从零开始完成了一个 Spring Boot + Vue 前后端分离的项目。从环境搭建、后端开发、前端开发到项目部署,我们详细介绍了每个步骤的具体实现。希望本文能够帮助大家掌握这一技术栈的实战应用,提升自己的开发能力。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐