使用 VUE + SpringBoot 实现前后端分离案例

Posted Yan Yang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用 VUE + SpringBoot 实现前后端分离案例相关的知识,希望对你有一定的参考价值。

VUE + SpringBoot 实现前后端分离

1. VUE 项目结构

在这里插入图片描述


2. SpringBoot 项目结构

在这里插入图片描述


2. pom.xml (Maven项目依赖)

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yy.mybatis-plus</groupId>
    <artifactId>mybatis-plus-demo</artifactId>
    <version>1.0.1</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

3. application.properties (配置文件)

server.port=8888
#mysql
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8:00
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# mybatis 配置 slq 打印日志
#logging.level.com.yy.mp.mapper=debug

# mybatis-plus 配置 slq 打印日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4. 前端 VUE 界面

4.1 index.html

<!DOCTYPE html>
<html lang="en"
      xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../js/vue.js"></script>
    <script src="../../js/jquery.js"></script>
</head>
<body>
<a href="/views/11_demo_list/input.html">添加</a>
<div id="app">
    <ul>
        <li v-for="e in emps" v-on:click="clickMeVue($event,e)">
            <!-- {{e.sex | sexFilter}}:管道操作,把左边的数据作为右边的参数 -->
            {{e.id}}-{{e.name}}-{{e.age}}}
            <!--
                e.id    一个变量
                input.html?id=  字符串
                目的拼接出 href url路径
            -->
            <a v-bind:href="'input.html?id=' + e.id">编辑</a>
        </li>
    </ul>
</div>

<script>
    var vue = new Vue({
        el: "#app",
        data: {
            emps: {}
        },
        mounted: function () {
            let _this = this;
            $.get('Http://localhost:8888/employees', function (data) {
                _this.emps = data;
            })
        }
    });
</script>
</body>
</html>

4.2 input.html

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/js/jquery.js"></script>
    <script src="/js/jquery.form.js"></script>
    <script src="/js/vue.js"></script>
    <script>
        //获取url上的请求参数
        function getParams() {
            //获取问号及问号后面的内容
            var url = window.location.search;
            var params = new Object();
            if (url.indexOf("?") != -1) {
                //截取问号后面的内容,再使用&分割多个属性
                var arr = url.substr(1).split("&");
                for (var i = 0; i < arr.length; i++) {
                    //使用=分割为keyvalue
                    var keyValue = arr[i].split("=");
                    params[keyValue[0]] = keyValue[1];
                }
            }
            return params;
        }

    </script>
</head>
<body>
    <div id="app">
        <form id="formId">
            <input type="hidden" name="id" v-model="emp.id">
            名称:<input type="text" name="name" v-model="emp.name"><br/>
            年龄:<input type="text" name="age" v-bind:value="emp.age"><br>
            <input type="button" id="btn" @click="submitForm()" value="提交">
        </form>
    </div>
    <script>
        let vue = new Vue({
            el: '#app',
            data: {
                emp: []
            },
            methods: {
                submitForm: function () {
                    // $.post(url, 表单参数序列化, function(data){...})

                    // 点击按钮时,发起起步请求,提交表单(异步表单提交)
                    // $("#formId").ajaxSubmit();   // 将表单转成异步表单,并提交
                    // $("#formId").ajaxForm();     // 将表单转成异步表单,不提交
                    $("#formId").ajaxSubmit({
                       url: "http://localhost:8888/employees",
                       type: "POST",
                        success: function (data) {
                           if (data) {
                               // 操作成功跳转
                               window.location.href = "input.html";
                           }
                        }
                    });
                }
            },
            mounted: function () {
                let _this = this;
                $.ajax({
                    url: "http://localhost:8888/employees/" + getParams().id,
                    type: "GET",
                    success: function (data) {
                        console.log(_this);
                        _this.emp = data;
                    }
                });
            }
        });
    </script>
</body>
</html>

5. 后端界面

5.1 EmployeeController 控制器

package com.yy.mp.web.controller;

import com.yy.mp.domain.Employee;
import com.yy.mp.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: mybatis-plus-demo
 * @ClassName: EmployeeController
 * @description:
 * @author: YanYang
 * @create: 2021-06-27 15:00
 **/
@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @GetMapping
    public List<Employee> list() {
        return employeeService.list();
    }

    @PostMapping
    public boolean saveOrUpdate(Employee employee) {
        if (employee.getId() != null) {
            return employeeService.updateById(employee);
        }
        return employeeService.save(employee);
    }

    @GetMapping("/{id}")
    public Employee input(@PathVariable Long id) {
        return employeeService.getById(id);
    }
}

5.2 EmployeeMapper 接口

public interface EmployeeMapper extends BaseMapper<Employee> {}

5.3 IEmployeeService (Service层接口)

package com.yy.mp.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yy.mp.domain.Employee;
import com.yy.mp.qo.EmployeeQueryObject;

/**
 * 自定义 mybatis-plus 服务层接口
 * 1> 自定义接口 IEmployeeService
 * 2> 继承通用接口 IService
 * 3> 指定泛型,即操作实体类型
 */
public interface IEmployeeService extends IService<Employee> {
}

5.4 EmployeeServiceImpl (Service实现层)

package com.yy.mp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.mp.domain.Employee;
import com.yy.mp.mapper.EmployeeMapper;
import com.yy.mp.qo.EmployeeQueryObject;
import com.yy.mp.service.IEmployeeService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 自定义 mybatis-plus 服务层接口实现类
 * 1> 自定义类 EmployeeServiceImpl
 * 2> 实现自定义接口:IEmployeeService
 * 3> 继承通用接口 IService 实现类:ServiceImpl
 * 4> 指定2个泛型:1:操作实体类 mapper 接口;2:操作实体对象类型:Employee
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
}

6. Config (跨域请求设置)

package com.yy.mp.config;

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 Config implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 添加映射路径
        registry.addMapping("/**")
                // 放行哪些原始域
                // .allwedOrigins("*")  // 2.2 之前的版本用的
                .allowedOriginPatterns("*")
                // 是否发送 Cookie 信息
                .allowCredentials(true)
                // 放行哪些原始域(请求方式)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 放行哪些头部信息
                .allowedHeaders("*")
                // 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
                .exposedHeaders("Header1", "Header2");
    }
}

以上是关于使用 VUE + SpringBoot 实现前后端分离案例的主要内容,如果未能解决你的问题,请参考以下文章

前后端分离项目(vue+springboot)集成pageoffice实现在线编辑office文件

Vue +Springboot+shiro实现前后端分离权限控制

Springboot + Vue + shiro 实现前后端分离权限控制

Springboot项目中运用vue+ElementUI+echarts前后端交互实现动态圆环图

springboot可以前后端分离吗

vue3+SpringBoot+postgresql 项目前后端传参