Springboot+Vue整合笔记【超详细】

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 目前很多公司的开发模式都是前后的分离的分工模式,这样能够做到各司其职,提高开发的效率。之前也有文章介绍了springboot项目和vue创建一个简单的前端项目,这篇文章则是将springboot和vue进行简单的整合,实现一个简单的登录页面。

1 前言


目前很多公司的开发模式都是前后的分离的分工模式,这样能够做到各司其职,提高开发的效率。之前也有文章介绍了springboot项目和vue创建一个简单的前端项目,这篇文章则是将springboot和vue进行简单的整合,实现一个简单的登录页面。


最后本文的源码都会同步至github,欢迎下载使用和star!


2 正文


先介绍下本文的开发工具,后端使用的java的版本是jdk1.8,框架是springboot,开发工具是idea,前端则是使用vue.js,开发工具是vs code。


本文的前提条件是需要对springboot和vue.js 有个一定简单的了解。


关于如何使用idea创建一个springboot项目可以参考:SpringBoot入门:使用IDEA和Eclipse构建第一个SpringBoot项目


如何创建一个vue前端项目可以参考: Vue学习笔记(一):从零开始创建一个Vue前端项目


一、后端Springboot项目开发:


这里先准备下数据,创建一个user表,并插入数据,sql如下:


CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
 `email` varchar(255) NOT NULL COMMENT '邮箱',
 `password` varchar(255) NOT NULL COMMENT '密码',
 `username` varchar(255) NOT NULL COMMENT '姓名',
 PRIMARY KEY (`id`),
 UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', '1@qq.com', '123456', '张三');
INSERT INTO `user` VALUES ('2', '2@qq.com', '234567', '李四');
INSERT INTO `user` VALUES ('3', '3@qq.com', '345678', '王五');
复制代码


首先创建一个springboot项目,然后在pom文件中引入相关依赖:


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springboot</groupId>
    <artifactId>springbootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootdemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        <!--io工具类-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!--运用SpringBoot 插件  使用spring-boot-devtools模块的应用,当classpath中的文件有改变时,会自动重启!-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
复制代码


application.properties文件,添加配置内容如下:


## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=root
spring.datasource.password=jiang
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Mybatis 配置
# 配置为 com.pancm.bean 指向实体类包路径。
mybatis.typeAliasesPackage=com.springboot.bean
# 配置为 classpath 路径下 mapper 包下,* 代表会扫描所有 xml 文件。
mybatis.mapperLocations=classpath\:mapper/*.xml
复制代码


开始编写核心逻辑代码:


新建一个User.java实体类,代码如下:


package com.springboot.springbootdemo.bean;
public class User {
    private long id;
    private String email;
    private String password;
    private String username;
    public long getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}
复制代码


然后再新建一个dao文件:


package com.springboot.springbootdemo.dao;
import com.springboot.springbootdemo.bean.User;
import org.apache.ibatis.annotations.*;
import org.springframework.data.repository.query.Param;
import java.util.List;
@Mapper
public interface UserDao {
    /**
     * 新增数据
     */
    @Insert("insert into user(id,email,password,username) values (#{id},#{email},#{password},#{username})")
    void addUser(User user);
    /**
     * 修改数据
     */
    @Update("update user set username=#{username},password=#{password} where id=#{id}")
    void updateUser(User user);
    /**
     * 删除数据
     */
    @Delete("delete from user where id=#{id}")
    void deleteUser(int id);
    /**
     * 根据查询数据
     *
     */
    @Select("select id,email,password,username from user where username=#{userName}")
    User findByName(@Param("userName") String userName);
    /**
     * 查询所有数据
     */
    @Select("select id,email,password,username FROM user")
    List<User> findAll();
}
复制代码


然后就是service和UserServiceImpl文件:


userservice:


package com.springboot.springbootdemo.service;
import com.springboot.springbootdemo.bean.User;
import java.util.List;
public interface UserService {
    /**
     * 新增用户
     * @param user
     * @return
     */
    boolean addUser(User user);
    /**
     * 修改用户
     * @param user
     * @return
     */
    boolean updateUser(User user);
    /**
     * 删除用户
     * @param id
     * @return
     */
    boolean deleteUser(int id);
    /**
     * 根据名字查询用户信息
     * @param userName
     */
    User findUserByName(String userName);
    /**
     * 查询所有数据
     * @return
     */
    List<User> findAll();
}
复制代码


UserServiceImpl文件:


package com.springboot.springbootdemo.service;
import com.springboot.springbootdemo.bean.User;
import com.springboot.springbootdemo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public boolean addUser(User user) {
        boolean flag=false;
        try{
            userDao.addUser(user);
            flag=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }
    @Override
    public boolean updateUser(User user) {
        boolean flag=false;
        try{
            userDao.updateUser(user);
            flag=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }
    @Override
    public boolean deleteUser(int id) {
        boolean flag=false;
        try{
            userDao.deleteUser(id);
            flag=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }
    @Override
    public User findUserByName(String userName) {
        return userDao.findByName(userName);
    }
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
}
复制代码


最后就是controller文件:


package com.springboot.springbootdemo.controller;
import com.springboot.springbootdemo.bean.User;
import com.springboot.springbootdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/do/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public boolean addUser(@RequestBody User user) {
        System.out.println("新增数据:");
        return userService.addUser(user);
    }
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public boolean updateUser(@RequestBody User user) {
        System.out.println("更新数据:");
        return userService.updateUser(user);
    }
    @RequestMapping(value = "/user", method = RequestMethod.DELETE)
    public boolean delete(@RequestParam(value = "id", required = true) int Id) {
        System.out.println("删除数据:");
        return userService.deleteUser(Id);
    }
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public User findByUserName(@RequestParam(value = "userName", required = true) String userName) {
        System.out.println("查询数据:");
        return userService.findUserByName(userName);
    }
    @RequestMapping(value = "/userAll", method = RequestMethod.GET)
    public List<User> findByUserAge() {
        System.out.println("查询所有数据:");
        return userService.findAll();
    }
}
复制代码


然后启动项目,进行测试:


微信截图_20220519221805.png


这里后端的接口基本就开发完成了,接着开发前端的vue项目。


二、前端Vue项目开发:


这里的前端的开发是在前面提到的那篇文章的demo基础上进行开发。


先引入一些组件,在终端窗口输入下面的命令:


#引入axios
 cnpm install axios --save-dev
复制代码


然后在main.js文件中引入,main.js文件如下:


// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import './plugins/element.js'
//引入axios
16 import axios from 'axios'
17 Vue.prototype.$ajax = axios
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
复制代码


接着在componment文件夹下新建一个页面:


<template>
  <div class="layout">
    <Layout>
      <Content :style="{padding: '0 50px'}">
        <Card>
          <div style="min-height: 200px;">
            <v-table
              is-horizontal-resize
              style="width:100%"
              :columns="columns"
              :table-data="tableData"
              row-hover-color="#eee"
              row-click-color="#edf7ff"
            ></v-table>
          </div>
        </Card>
      </Content>
    </Layout>
  </div>
</template>
<script>
  export default {
    name: "main-page",
    data() {
      return {
        tableData: [],
        columns: [
          {field: 'id', title: '编号', width: 80, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'email', title: '邮箱', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'password', title: '密码', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'username', title: '姓名', width: 280, titleAlign: 'center', columnAlign: 'left',isResize:true}
        ]
      }
    },
    created() {
        //这里直接在created函数中使用axios的get请求向后台获取用户信息数据
        // 在实际开发中可以卸载apiadress.js中配置具体的method对应的路径和接口,这个
        //后面完善功能的情况下再进行介绍
        this.$ajax('http://localhost:8080/do/user/userAll').then(res => {
         this.tableData = res.data
          console.log(res.data);
       }).catch(function (error) {
          console.log(error);
     });
  }
  }
</script>
<style scoped>
  .layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    height: 100%;
  }
  .layout-logo{
    width: 100px;
    height: 30px;
    background: #5b6270;
    border-radius: 3px;
    float: left;
    position: relative;
    top: 15px;
    left: 20px;
    font-weight: bold;
    text-align: center;
    color: #49ffcc;
  }
  .layout-nav{
    width: 420px;
    margin: 0 auto;
    margin-right: 20px;
  }
  .layout-footer-center{
    text-align: center;
  }
</style>
复制代码


接着在index.js文件中加入该组件:


import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HelloDemo from '@/components/HelloDemo'
import zicomponent from '@/components/zicomponent'
import fucomponent from '@/components/fucomponent'
import MainPage from '@/components/MainPage'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path:'/hello',
      name:'HelloDemo',
      component:HelloDemo
    },
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/zi',
      name: 'zicomponent',
      component: zicomponent
    },
    {
      path: '/fu',
      name: 'fucomponent',
      component: fucomponent
    },
    {
      path: '/main',
      name: 'MainPage',
      component: MainPage
    }
  ]
})
复制代码


接着输入npm run dev,编译项目:


微信截图_20220519221825.png


478dc69205e74a87ae298268db057b6a~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


注意这里因为vue是8081端口,而springboot项目是8080端口,所以查不出数据。


94e6c4e263dc407c8d453199506f9e31~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


这里可以看到报跨域的错误了。所以我们要对前端的代码进行下处理:


main.js文件加入下面的代码:


08a1ae2c18ab46b9bae136e090fbefcf~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


// 设置全局的axios
Vue.prototype.$axios=Axios
// 设置基本路径
Axios.defaults.baseURL='/api'
复制代码


config/index.js文件,在proxyTable里添加如下代码:


5c13205ed8d74bfa9d120cb2626f37a5~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


//代理请求路径
    proxyTable: {
      '/api':{
        target:"http://localhost:8080/",
        changeOrigin:true,
        pathRewrite:{
          '^/api':''
        }
      }
    },
复制代码


ceaa7b0eedd24bb59de2e65a6624ff9d~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


最后重启下前端(我这里需要重启下不然没生效),然后编译:


7c01e9f6b2af4aa689a6567ae15317f7~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


3 总结


上面就是如果使用简单的将springboot和vue进行一个简单的整合,后续将对这块进行完善和继续开发,有任何问题欢迎交流讨论。


另外所有实战文章的源码都会同步至github,有需要的欢迎下载使用。

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
3月前
|
前端开发 安全 Java
基于springboot+vue开发的会议预约管理系统
一个完整的会议预约管理系统,包含前端用户界面、管理后台和后端API服务。 ### 后端 - **框架**: Spring Boot 2.7.18 - **数据库**: MySQL 5.6+ - **ORM**: MyBatis Plus 3.5.3.1 - **安全**: Spring Security + JWT - **Java版本**: Java 11 ### 前端 - **框架**: Vue 3.3.4 - **UI组件**: Element Plus 2.3.8 - **构建工具**: Vite 4.4.5 - **状态管理**: Pinia 2.1.6 - **HTTP客户端
362 4
基于springboot+vue开发的会议预约管理系统
|
7月前
|
JavaScript 前端开发 Java
制造业ERP源码,工厂ERP管理系统,前端框架:Vue,后端框架:SpringBoot
这是一套基于SpringBoot+Vue技术栈开发的ERP企业管理系统,采用Java语言与vscode工具。系统涵盖采购/销售、出入库、生产、品质管理等功能,整合客户与供应商数据,支持在线协同和业务全流程管控。同时提供主数据管理、权限控制、工作流审批、报表自定义及打印、在线报表开发和自定义表单功能,助力企业实现高效自动化管理,并通过UniAPP实现移动端支持,满足多场景应用需求。
646 1
|
8月前
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
513 7
|
4月前
|
前端开发 JavaScript Java
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
本系统基于SpringBoot与Vue3开发,实现校园食堂评价功能。前台支持用户注册登录、食堂浏览、菜品查看及评价发布;后台提供食堂、菜品与评价管理模块,支持权限控制与数据维护。技术栈涵盖SpringBoot、MyBatisPlus、Vue3、ElementUI等,适配响应式布局,提供完整源码与数据库脚本,可直接运行部署。
241 6
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
|
6月前
|
监控 数据可视化 JavaScript
springboot + vue的MES系统生产计划管理源码
MES系统(制造执行系统)的生产计划管理功能是其核心模块之一,涵盖生产计划制定与优化、调度排程、进度监控反馈、资源管理调配及可视化报告五大方面。系统基于SpringBoot + Vue-Element-Plus-Admin技术栈开发,支持多端应用(App、小程序、H5、后台)。通过实时数据采集与分析,MES助力企业优化生产流程,适用于现代化智能制造场景。
304 1
|
7月前
|
供应链 JavaScript BI
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
这是一款专为小微企业打造的 SaaS ERP 管理系统,基于 SpringBoot+Vue+ElementUI+UniAPP 技术栈开发,帮助企业轻松上云。系统覆盖进销存、采购、销售、生产、财务、品质、OA 办公及 CRM 等核心功能,业务流程清晰且操作简便。支持二次开发与商用,提供自定义界面、审批流配置及灵活报表设计,助力企业高效管理与数字化转型。
617 2
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
|
8月前
|
JavaScript 前端开发 Java
Spring Boot 与 Vue.js 前后端分离中的数据交互机制
本文深入探讨了Spring Boot与Vue.js在前后端分离架构下的数据交互机制。通过对比传统`model.addAttribute()`方法与RESTful API的设计,分析了两者在耦合性、灵活性及可扩展性方面的差异。Spring Boot以RESTful API提供数据服务,Vue.js借助Axios消费API并动态渲染页面,实现了职责分明的解耦架构。该模式显著提升了系统的灵活性和维护性,适用于复杂应用场景如论坛、商城系统等,为现代Web开发提供了重要参考。
790 0
|
11月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的留守儿童爱心网站设计与实现(计算机毕设项目实战+源码+文档)
博主是一位全网粉丝超过100万的CSDN特邀作者、博客专家,专注于Java、Python、PHP等技术领域。提供SpringBoot、Vue、HTML、Uniapp、PHP、Python、NodeJS、爬虫、数据可视化等技术服务,涵盖免费选题、功能设计、开题报告、论文辅导、答辩PPT等。系统采用SpringBoot后端框架和Vue前端框架,确保高效开发与良好用户体验。所有代码由博主亲自开发,并提供全程录音录屏讲解服务,保障学习效果。欢迎点赞、收藏、关注、评论,获取更多精品案例源码。
|
11月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的家政服务管理平台设计与实现(计算机毕设项目实战+源码+文档)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
|
11月前
|
JavaScript 搜索推荐 Java
基于SpringBoot+Vue实现的家乡特色推荐系统设计与实现(源码+文档+部署)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!

热门文章

最新文章