手把手教你搭建Spring Boot+Vue前后端分离

这篇具有很好参考价值的文章主要介绍了手把手教你搭建Spring Boot+Vue前后端分离。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1 什么是前后端分离

前后端分离是目前互联网开发中比较广泛使用的开发模式,主要是将前端和后端的项目业务进行分离,可以做到更好的解耦合,前后端之间的交互通过xml或json的方式,前端主要做用户界面的渲染,后端主要负责业务逻辑和数据的处理。
手把手教你搭建Spring Boot+Vue前后端分离

2 Spring Boot后端搭建

2.1 Mapper层

请参阅这篇文章https://blog.csdn.net/Mr_YanMingXin/article/details/118342143

此次项目的后端搭建就是在这个项目的基础上

2.2 Service层

接口:

/**
 * @author 17122
 */
public interface StudentService {
    /**
     * 添加一个学生
     *
     * @param student
     * @return
     */
    public int saveStudent(Student student);

    /**
     * 根据ID查看一名学生
     *
     * @param id
     * @return
     */
    public Student findStudentById(Integer id);

    /**
     * 查询全部学生
     *
     * @return
     */
    public List<Student> findAllStudent();

    /**
     * 根据ID删除一个
     *
     * @param id
     * @return
     */
    public int removeStudentById(Integer id);

    /**
     * 根据ID修改
     *
     * @param student
     * @return
     */
    public int updateStudentById(Student student);


}

实现类:

/**
 * @author 17122
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private XmlStudentMapper xmlStudentMapper;

    @Override
    public int saveStudent(Student student) {
        return xmlStudentMapper.saveStudent(student);
    }

    @Override
    public Student findStudentById(Integer id) {
        return xmlStudentMapper.findStudentById(id);
    }

    @Override
    public List<Student> findAllStudent() {
        return xmlStudentMapper.findAllStudent();
    }

    @Override
    public int removeStudentById(Integer id) {
        return xmlStudentMapper.removeStudentById(id);
    }

    @Override
    public int updateStudentById(Student student) {
        return xmlStudentMapper.updateStudentById(student);
    }
}
2.3 Controller层
/**
 * @author 17122
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 添加学生
     *
     * @param student
     * @return
     */
    @PostMapping("/save")
    public int saveStudent(@RequestBody Student student) {
        int result;
        try {
            result = studentService.saveStudent(student);
        } catch (Exception exception) {
            return -1;
        }
        return result;
    }

    /**
     * 查看全部
     *
     * @return
     */
    @GetMapping("/findAll")
    public List<Student> findAll() {
        return studentService.findAllStudent();
    }

    /**
     * 根据ID查看
     *
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") Integer id) {
        return studentService.findStudentById(id);
    }

    /**
     * 删除一个
     *
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    public int remove(@PathVariable("id") Integer id) {
        return studentService.removeStudentById(id);
    }

    /**
     * 修改学生信息
     *
     * @param student
     * @return
     */
    @PostMapping("/update")
    public int update(@RequestBody Student student) {
        return studentService.updateStudentById(student);
    }

}
2.4 配置类

解决跨域请求

/**
 * @author 17122
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

图解跨域问题:
手把手教你搭建Spring Boot+Vue前后端分离

3 Vue前端搭建

3.1 新建Vue_cli2.x项目
3.2 引入路由
npm install vue-router --save
3.3 新建文件

手把手教你搭建Spring Boot+Vue前后端分离

3.4 配置和测试路由
main.js配置
import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
    render: h => h(App),
    router
}).$mount('#app')
index.js
//注册路由
import Vue from 'vue';
import VueRouter from 'vue-router';
//引入路由
import index from '../view/index'
import update from "../view/update";
import selectAll from "../view/selectAll";
import selectOne from "../view/selectOne";
import insert from "../view/insert";

Vue.use(VueRouter);

const router = new VueRouter({
    routes: [
        {
            name: "主页重定向",
            path: "/",
            redirect: "/index"
        }, {
            name: "主页",
            path: "/index",
            component: index,
            children: [
                {
                    name: "修改操作",
                    path: "/update",
                    component: update,
                }, {
                    name: "查看全部",
                    path: "/selectAll",
                    component: selectAll,
                }, {
                    name: "查看一个",
                    path: "/selectOne",
                    component: selectOne,
                }, {
                    name: "添加一个",
                    path: "/insert",
                    component: insert,
                }
            ]
        }
    ]
})

export default router
App.vue
<template>
    <div id="app">
        <router-view/>
    </div>
</template>

<script>

export default {
    name: 'App',
}
</script>
index.vue
<template>
    <div>
        <router-link to="update">update</router-link>
        <br>
        <router-link to="selectAll"> selectAll</router-link>
        <br>
        <router-link to="selectOne"> selectOne</router-link>
        <br>
        <router-link to="insert"> insert</router-link>
        <br>
        <br>
        <router-view></router-view>
    </div>
</template>

<script>
export default {
    name: "index"
}
</script>

<style scoped>

</style>
insert.vue
<template>
    <div>
        insert
    </div>
</template>

<script>
export default {
    name: "insert"
}
</script>

<style scoped>

</style>
selectOne.vue
<template>
    <div>
        selectOne
    </div>
</template>

<script>
export default {
    name: "selectOne"
}
</script>

<style scoped>

</style>
selectAll.vue
<template>
    <div>
        selectAll
    </div>
</template>

<script>
export default {
    name: "selectAll"
}
</script>

<style scoped>

</style>
update.vue
<template>
    <div>
        update
    </div>
</template>

<script>
export default {
    name: "update"
}
</script>

<style scoped>

</style>
测试

启动项目

npm run serve

访问:http://localhost:8080/
手把手教你搭建Spring Boot+Vue前后端分离
点击相关标签时会显示响应页面

3.5 引入Element UI
npm i element-ui -S
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.config.productionTip = false
Vue.use(ElementUI)
new Vue({
    render: h => h(App),
    router
}).$mount('#app')
3.6 使用Element UI美化页面
index.vue
<template>
    <div>
        <el-menu class="el-menu-demo" mode="horizontal" :router="true">
            <el-menu-item index="/selectAll">全部学生</el-menu-item>
            <el-menu-item index="/insert">添加学生</el-menu-item>
            <el-menu-item index="/selectOne">查看学生</el-menu-item>
            <el-menu-item index="/update">修改学生</el-menu-item>
        </el-menu>
        <router-view></router-view>
    </div>
</template>

<script>
export default {
    name: "index"
}
</script>

<style scoped>

</style>
insert.vue
<template>
    <div>
        <el-form :model="ruleForm" status-icon  label-width="100px" class="demo-ruleForm" style="margin-top:30px;width: 30%;">
            <el-form-item label="姓名" prop="pass">
                <el-input type="text" v-model="ruleForm.name" ></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="checkPass">
                <el-input type="text" v-model="ruleForm.age" ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
export default {
    name: "insert",
    data() {
        return {
            ruleForm: {
                name: '',
                age: ''
            }
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    }
}
</script>

<style scoped>

</style>
selectOne.vue
<template>
    <div>
        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"
                 style="margin-top:30px;width: 30%;">
            <el-form-item label="ID" prop="pass">
                <el-input type="text" v-model="ruleForm.id"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="pass">
                <el-input type="text" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="checkPass">
                <el-input type="text" v-model="ruleForm.age"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
export default {
    name: "selectOne",
    data() {
        return {
            ruleForm: {
                id: '',
                name: '',
                age: ''
            }
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        }
    }
}
</script>

<style scoped>

</style>
selectAll.vue
<template>
    <div>
        <template>
            <el-table
                  :data="tableData"
                  style="width: 60%;margin-top:30px;">
                <el-table-column
                      prop="id"
                      label="ID"
                      width="180">
                </el-table-column>
                <el-table-column
                      prop="name"
                      label="姓名"
                      width="180">
                </el-table-column>
                <el-table-column
                      prop="age"
                      label="年龄">
                </el-table-column>
                <el-table-column
                      label="操作">
                    <template>
                        <el-button type="warning" size="small">修改</el-button>
                        <el-button type="danger" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </div>
</template>

<script>
export default {
    name: "selectAll",
    data() {
        return {
            tableData: []
        }
    }
}
</script>

<style scoped>

</style>
update.vue
<template>
    <div>
        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"
                 style="margin-top:30px;width: 30%;">
            <el-form-item label="ID" prop="pass">
                <el-input type="text" v-model="ruleForm.id"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="checkPass">
                <el-input type="text" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input type="text" v-model="ruleForm.age"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="warning" @click="submitForm('ruleForm')">修改</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
export default {
    name: "update",
    data() {
        return {
            ruleForm: {
                id: '',
                name: '',
                age: ''
            }
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        }
    }
}
</script>

<style scoped>

</style>
效果

手把手教你搭建Spring Boot+Vue前后端分离
手把手教你搭建Spring Boot+Vue前后端分离

3.7 整合axios与Spring Boot后端交互
npm install axios --save
insert.vue
<template>
    <div>
        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"
                 style="margin-top:30px;width: 30%;">
            <el-form-item label="姓名" prop="pass">
                <el-input type="text" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="checkPass">
                <el-input type="text" v-model="ruleForm.age"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm()">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import axios from 'axios'

export default {
    name: "insert",
    data() {
        return {
            ruleForm: {
                name: '',
                age: ''
            }
        };
    },
    methods: {
        submitForm() {
            axios.post("http://localhost:8081/student/save", this.ruleForm).then(function (resp) {
                console.log(resp)
            })
        },
    }
}
</script>

<style scoped>

</style>
selectOne.vue
<template>
    <div>
        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"
                 style="margin-top:30px;width: 30%;">
            <el-form-item label="ID" prop="pass">
                <el-input type="text" v-model="ruleForm.id"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="pass">
                <el-input type="text" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="checkPass">
                <el-input type="text" v-model="ruleForm.age"></el-input>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import axios from "axios";

export default {
    name: "selectOne",
    data() {
        return {
            ruleForm: {
                id: '',
                name: '',
                age: ''
            }
        };
    },
    methods: {
        getStudent() {
            const _this = this;
            axios.get("http://localhost:8081/student/findById/" + this.$route.query.id).then(function (resp) {
                _this.ruleForm = resp.data;
            })
        }
    },
    created() {
        this.getStudent();
    }
}
</script>

<style scoped>

</style>
selectAll.vue
<template>
    <div>
        <template>
            <el-table
                  :data="tableData"
                  style="width: 60%;margin-top:30px;">
                <el-table-column
                      prop="id"
                      label="ID"
                      width="180">
                </el-table-column>
                <el-table-column
                      prop="name"
                      label="姓名"
                      width="180">
                </el-table-column>
                <el-table-column
                      prop="age"
                      label="年龄">
                </el-table-column>
                <el-table-column
                      label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="small" @click="select(scope.row)">查看</el-button>
                        <el-button type="warning" size="small" @click="update(scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="remove(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </div>
</template>

<script>
import axios from "axios";

export default {
    name: "selectAll",
    data() {
        return {
            tableData: []
        }
    },
    methods: {
        getData() {
            const _this = this;
            axios.get("http://localhost:8081/student/findAll").then(function (resp) {
                _this.tableData = resp.data;
            })
        },
        remove(stu) {
            const _this = this;
            if (confirm("确定删除吗?")) {
                axios.delete("http://localhost:8081/student/remove/" + stu.id).then(function (resp) {
                    if (resp.data == 1) {
                        _this.getData();
                    }
                })
            }
        },
        select(stu) {
            this.$router.push({
                path: "/selectOne",
                query:{
                    id: stu.id
                }
            })
        },
        update(stu) {
            this.$router.push({
                path: "/update",
                query:{
                    id: stu.id
                }
            })
        }
    },
    created() {
        this.getData();
    }
}
</script>

<style scoped>

</style>
update.vue
<template>
    <div>
        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"
                 style="margin-top:30px;width: 30%;">
            <el-form-item label="ID">
                <el-input type="text" v-model="ruleForm.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名">
                <el-input type="text" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="年龄">
                <el-input type="text" v-model="ruleForm.age"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="warning" @click="submitForm()">修改</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import axios from "axios";

export default {
    name: "update",
    data() {
        return {
            ruleForm: {
                id: '',
                name: '',
                age: ''
            }
        };
    },
    methods: {
        submitForm() {
            axios.post("http://localhost:8081/student/update", this.ruleForm).then(function (resp) {
                console.log(resp)
            })
        },
        getStudent() {
            const _this = this;
            axios.get("http://localhost:8081/student/findById/" + this.$route.query.id).then(function (resp) {
                _this.ruleForm = resp.data;
            })
        }
    },
    created() {
        this.getStudent();
    }
}
</script>

<style scoped>

</style>

4 总结

手把手教你搭建Spring Boot+Vue前后端分离

源码获取

源码获取方式,关注下面公众号【扯编程的淡】,回复关键字【1204】
手把手教你搭建Spring Boot+Vue前后端分离
手把手教你搭建Spring Boot+Vue前后端分离文章来源地址https://www.toymoban.com/news/detail-400507.html

到了这里,关于手把手教你搭建Spring Boot+Vue前后端分离的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • vue系列(三)——手把手教你搭建一个vue3管理后台基础模板

    目录 一、前言: 二、网站页面分析 三、开发步骤 (一)、安装element (二)、安装使用svg插件 (三)、编写主界面框架代码  (四)、编写菜单栏  (五)、新建页面及路由 (六)、定制页面标签栏 第一步: 第二步: (七)、修改封装菜单栏 (八)、添加面包屑 四、结

    2023年04月24日
    浏览(47)
  • 手把手搭建 java spring boot 框架 maven 项目 web 网址访问

    第一步我们去  spring boot 官网创建项目并下载压缩包  创建项目网址: Spring Initializr https://start.spring.io/ 我们添加一个 srping web 的拓展包 接下来我们点击 generate 创建 并下载压缩包即可 接下来我们将压缩文件包解压到项目根目录使用编辑器打开即可,如果编辑器提示 点击构

    2024年04月23日
    浏览(40)
  • 手把手教你使用vue2搭建微前端micro-app

    ​ 本文主要讲述新手小白怎么搭建micro-app,几乎是每一步都有截图说明。上手应该很简单。 这段时间在网上找了很多有关微前端相关的知识,起初本来是想着先搭建一个single-spa,但是奈何网上能找到的内容都是千篇一律。我也是搭了好久没搭出来。不知道为啥,反正就是一

    2024年01月20日
    浏览(42)
  • 手把手教你通过 Docker 部署前后端分离项目(亲测可用)

    安装Docker 安装Nginx 安装Mysql 部署SpringBoot项目 部署Vue项目 一、安装Docker 1、安装: 2、启动/停止/重启docker服务 3、查看docker版本信息 4、运行helloword,因为不存在此镜像,docker会自动下载运行本镜像 5、查看所有docker镜像 二、安装Nginx 1、拉取Nginx镜像文件 2、查看下载好的镜像

    2023年04月24日
    浏览(45)
  • 手把手教你从0搭建SpringBoot项目

    用到的工具:idea 2021、Maven 3.6.3、postman 框架:SpringBoot、Mybatis 数据库:Mysql8.0.30 安装配置参考博文 注意: 1.下载maven注意idea与Maven版本的适配: 2.为了避免每次创建项目都要改Maven配置,可以修改idea创建新项目的设置 二、安装数据库 mysql8安装参考博文 **注意:**连接不上往

    2024年02月03日
    浏览(37)
  • 手把手教你搭建自己本地的ChatGLM

    如果能够本地自己搭建一个ChatGPT的话,训练一个属于自己知识库体系的人工智能AI对话系统,那么能够高效的处理应对所属领域的专业知识,甚至加入职业思维的意识,训练出能够结合行业领域知识高效产出的AI。这必定是十分高效的生产力工具,且本地部署能够保护个人数

    2024年02月03日
    浏览(52)
  • 手把手教你,本地RabbitMQ服务搭建(windows)

    前面已经对RabbitMQ介绍了很多内容,今天主要是和大家搭建一个可用的RabbitMQ服务端,方便后续进一步实操与细节分析 跟我们跑java项目,要装jdk类似。rabbitMQ是基于Erlang开发的,因此安装rabbitMQ服务器之前,需要先安装Erlang环境。 【PS: 我已经上传了对应资源,windows可直接下载

    2024年02月14日
    浏览(42)
  • 手把手教你5分钟搭建RabbitMq开发环境

    演示环境 1、使用Vagrant 和 VirtualBox创建linux虚拟机 不知道Vagrant怎么使用的可以看这里。 ①在cmd窗口执行命令 vagrant init generic/centos7 ,初始化linux启动环境 ②执行启动命令 vagrant up 启动Linux虚拟机 ③修改当前目录的Vagrantfile文件,为虚拟机配置内网ip,后面登录的时候会用到

    2023年04月12日
    浏览(47)
  • 手把手教你搭建ARM32 QEMU环境

    我们知道嵌入式开发调试就要和各种硬件打交道,所以学习就要专门购买各种开发版,浪费资金,开会演示效果还需要携带一大串的板子和电线,不胜其烦。然而Qemu的使用可以避免频繁在开发板上烧写版本,如果进行的调试工作与外设无关,仅仅是内核方面的调试,Qemu模拟

    2024年02月19日
    浏览(48)
  • 手把手教你搭建一个Minecraft 服务器

    这次,我们教大家如何搭建一个我的世界服务器 首先,我们来到这个网站 MCVersions.net - Minecraft Versions Download List MCVersions.net offers an archive of Minecraft Client and Server jars to download, for both current and old releases! https://mcversions.net/   在这里,我们点击对应的版本,从左到右依次是稳定版

    2024年02月09日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包