溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue怎么結合Springboot實現(xiàn)前后端分離

發(fā)布時間:2022-10-13 13:40:19 來源:億速云 閱讀:252 作者:iii 欄目:開發(fā)技術

今天小編給大家分享一下Vue怎么結合Springboot實現(xiàn)前后端分離的相關知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

項目介紹

用戶列表頁面開發(fā),可以實現(xiàn)簡單的查詢,刪除,修改,和添加用戶信息功能。前端使用vue框架,后端使用springboot框架,一個簡單的vue+springboot前后端分離小項目。

1、前端html頁面編寫

頁面:

Vue怎么結合Springboot實現(xiàn)前后端分離

代碼:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>vue系列課程</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="external nofollow" >
</head>
<body>
    <div id="app">

        <div>
            <!--標題行-->
            <div>
                <div class="col-sm-6 col-sm-offset-3"><h1>用戶列表</h1></div>
            </div>
            <!--數(shù)據(jù)行-->
            <div>
                <div class="col-sm-10 col-sm-offset-1">
                    <!--添加按鈕-->
                    <a href="" class=" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" btn-success btn-sm">添加</a>
                    <!--列表-->
                    <table class="table table-striped table-bordered" style="margin-top: 10px;">
                        <tr>
                            <td>編號</td>
                            <td>姓名</td>
                            <td>工資</td>
                            <td>年齡</td>
                            <td>個人簡介</td>
                            <td>操作</td>
                        </tr>
                        <tr v-for="user in users">
                            <td>{{user.id}}</td>
                            <td>{{user.name}}</td>
                            <td>{{user.salary}}</td>
                            <td>{{user.age}}</td>
                            <td>{{user.description}}</td>
                            <td>
                                <a href="" class=" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" btn btn-danger btn-sm">刪除</a>
                                <a href="" class=" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" btn btn-info btn-sm">修改</a>
                            </td>
                        </tr>

                    </table>
                    <!--添加 和 修改表單-->
                    <form>
                        <div>
                            <label>編號</label>
                            <div >
                                <p>0001</p>
                            </div>
                        </div>
                        <div>
                            <label for="name">姓名</label>
                            <input type="text" id="name" placeholder="請輸入姓名">
                        </div>
                        <div>
                            <label for="salary">工資</label>
                            <input type="text" id="salary" placeholder="請輸入工資">
                        </div>
                        <div>
                            <label for="age">年齡</label>
                            <input type="text" id="age" placeholder="請輸入年齡">
                        </div>
                        <div>
                            <label for="description">個人簡介</label>
                            <input type="text" id="description" placeholder="請輸入個人簡介">
                        </div>

                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>

    </div>
</body>
</html>
<!--引入axios-->
<script src="js/axios.min.js"></script>
<!--引入vue-->
<script src="js/vue.js"></script>
<script>
    var app = new Vue({
        el: "#app",
        data:{
            msg:"vue 生命周期",
            users:[],
        },
        methods:{

        },
        computed:{

        },
        created(){
            //發(fā)送axios請求
            /*axios.get("http://localhost:8989/users").then(res=>{
               this.users = res.data;
            });*/
            this.users =[{id:1,name:"小陳",age:23,salary:2300,description:"他是一個小白!!!"}]
        },
    });
</script>

我們將html頁面放到如下位置:

Vue怎么結合Springboot實現(xiàn)前后端分離

js目錄下存放vue和axios資源文件。

2、springboot框架搭建

2.1、項目創(chuàng)建

1、新建maven項目,取名為vue_day3_admin

Vue怎么結合Springboot實現(xiàn)前后端分離

2、引入sprinboot-web依賴

<dependencies>
    <!--引入springboot-web依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

3、編寫啟動類AdminApplication

package com.xiao;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class,args);
    }
}

4、測試

Vue怎么結合Springboot實現(xiàn)前后端分離

2.2、連接數(shù)據(jù)庫

1、創(chuàng)建vue_day3數(shù)據(jù)庫

CREATE TABLE t_user(
 id INT(6) PRIMARY KEY AUTO_INCREMENT,
 NAME VARCHAR(40),
 salary DOUBLE(7,2),
 age INT(3),
 des VARCHAR(200)
);

2、引入數(shù)據(jù)庫相關依賴

<!--整合mybatis 引入依賴-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>5.1.38</scope>
</dependency>
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</version>
</dependency>
</dependencies>

3、application.properties配置文件編寫

server.port=8990

# 整合mybatis

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/vue_day3?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root

# 指定mapper出現(xiàn)的位置
mybatis.mapper-locations=classpath:com/xiao/mapper/*.xml
mybatis.type-aliases-package=com.xiao.entity

# 展示執(zhí)行過程中sql語句
logging.level.com.xiao.dao=debug

4、springboot連接mysql數(shù)據(jù)庫

4.1、打開Data Sources and Deivers 輸入數(shù)據(jù)庫user和password,并選擇要連接的數(shù)據(jù)庫。

Vue怎么結合Springboot實現(xiàn)前后端分離

4.2、設置時區(qū)為UTC

Vue怎么結合Springboot實現(xiàn)前后端分離

5、啟動測試一下

Vue怎么結合Springboot實現(xiàn)前后端分離

沒有任何問題。

2.3、項目完整依賴

<?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>org.example</groupId>
    <artifactId>vue_day3_admin</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--繼承springboot父項目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>
    <dependencies>
        <!--引入springboot-web依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--整合mybatis 引入依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>5.1.38</scope>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.1</version>
        </dependency>
        <!--本地測試-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.12.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3、編寫entity層

創(chuàng)建user實體類

package com.xiao.entity;

public class User {
    private Integer id;
    private String name;
    private Double salary;
    private Integer age;
    private String des;

    public User() {
    }

    public User(Integer id, String name, Double salary, Integer age, String des) {
        this.id = id;
        this.name = name;
        this.salary = salary;
        this.age = age;
        this.des = des;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name="" + name + """ +
                ", salary=" + salary +
                ", age=" + age +
                ", des="" + des + """ +
                "}";
    }
}

4、查詢用戶信息

4.1、后端代碼編寫

1、UserDAO編寫

package com.xiao.dao;

import com.xiao.entity.User;

import java.util.List;

public interface UserDAO {

    //查詢所有用戶信息
    List<User> findAll();
}

2、UserDAOMapper.xml編寫

resources下創(chuàng)建如下目錄

Vue怎么結合Springboot實現(xiàn)前后端分離

代碼:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xiao.dao.UserDAO">
    <!--findAll-->
    <select id="findAll" resultType="User">
        select id,name,salary,age,des from t_user;
    </select>
</mapper>

3、service層編寫

UserService 接口

package com.xiao.service;

import com.xiao.entity.User;
import java.util.List;

public interface UserService {
    //查詢所有用戶方法
    List<User> findAll();
}

UserServiceImpl 實現(xiàn)類

package com.xiao.service;

import com.xiao.dao.UserDAO;
import com.xiao.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service //代表這是一個業(yè)務層組件 作用:用來在spring工廠中創(chuàng)建一個userServiceImpl對象
@Transactional //代表給類中所有的方法加入事務控制
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDAO userDAO;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS) //方法上聲明事務注解
    public List<User> findAll() {
        return userDAO.findAll();
    }
}

4、進行test測試

Vue怎么結合Springboot實現(xiàn)前后端分離

BasicTest

package com.xiao.test;
import com.xiao.AdminApplication;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = AdminApplication.class) //指定入口類@RunWith(SpringRunner.class)  //啟動工廠public class BasicTest {}

TestUserService

package com.xiao.test;
import com.xiao.service.UserService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class TestUserService extends BasicTest 
{
    @Autowired private UserService userService;
    @Test public void findAll() {
        userService.findAll().forEach(user -> System.out.println(user));
    }
}

4.2、前端代碼編寫

1、在created()函數(shù)中添加axios請求

# 生命周期鉤子:生命周期函數(shù)
初始化階段
1.beforeCreate vue實例自身事件生命周期初始化
2.created 完成自定義data methods computed 注入和校驗 推薦
3.beforeMount將el指向html編譯為模板,并沒有完成模板注入
4.Mounted將編譯模板進行數(shù)據(jù)注入,并將注入完成模板形成虛擬dom替換el指向原始dom

代碼:

var app = new Vue({
    el: "#app",
    data:{
        msg:"vue 生命周期",
        users:[], //定義一個users空數(shù)組,用來存貯所有用戶的信息
    },
    methods:{

    },
    computed:{

    },
    created(){ //執(zhí)行 data methods computed 等完成注入和校驗
        //發(fā)送axios請求
        axios.get("http://localhost:8990/users").then(res=>{
            console.log(res.data);
            this.users = res.data;
        }); //es6 箭頭函數(shù) 注意:箭頭函數(shù)內(nèi)部沒有自己this  簡化 function(){} //存在自己this
    },
});

5、添加用戶信息

5.1、后端代碼編寫

1、UserDAO接口層

//查詢所有用戶信息
List<User> findAll();

2、UserDAOMapper.xml

<!--save-->
<insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
    insert into t_user values (#{id},#{name},#{salary},#{age},#{des})
</insert>

使用 mysql 自增長序列,新插入一條數(shù)據(jù)時,怎么得到主鍵?

加入以下屬性即可:

useGeneratedKeys=“true” keyProperty=“id”

useGeneratedKeys 取值范圍true、false 默認值是:false。 含義:設置是否使用JDBC的getGenereatedKeys方法獲取主鍵并賦值到keyProperty設置的領域模型屬性中。

keyProperty 取id的key值,主要是在主鍵是自增的情況下,添加成功后可以直接使用主鍵值,其中keyProperty的值是對象的屬性值,不是數(shù)據(jù)庫表中的字段名。

3、service層編寫

UserService

//保存用戶信息
void save(User user);

UserServiceImpl

@Override
public void save(User user) {
    userDAO.save(user);
}

4、UserController控制類

//添加員工信息接口
@PostMapping("saveOrUpdate")
public void saveOrUpdate(@RequestBody User user){
    System.out.println(user);
    userService.save(user);
}

5.2、前端代碼編寫

1、form表單中添加v-model雙向綁定

</div>
<div>
    <label for="name">姓名</label>
    <input type="text" v-model="user.name" id="name" placeholder="請輸入姓名">
</div>
<div>
    <label for="salary">工資</label>
    <input type="text" v-model="user.salary" id="salary" placeholder="請輸入工資">
</div>
<div>
    <label for="age">年齡</label>
    <input type="text" v-model="user.age" id="age" placeholder="請輸入年齡">
</div>
<div>
    <label for="description">個人簡介</label>
    <input type="text" v-model="user.des" id="description" placeholder="請輸入個人簡介">
</div>
<button type="button" class="btn btn-primary btn-block" @click="saveOrUpdate">提交</button>

2、給提交按鈕綁定 saveOrUpdate方法

var app = new Vue({
        el: "#app",
        data:{
            msg:"vue 生命周期",
            users:[], //定義一個users空數(shù)組,用來存貯所有用戶的信息
            user:{},  //定義了一個空的json對象
        },
        methods:{
            saveOrUpdate(){ //保存或者修改方法
                //發(fā)送添加的請求
                console.log(this.user);
                axios.post("http://localhost:8990/saveOrUpdate",this.user).then(res=>{
                    this.user={}; //添加成功,清空數(shù)據(jù)
                    alert("用戶信息更新成功!");
                    //更新原始列表的數(shù)據(jù)
                    this.findAll(); //調(diào)用查詢所有
                }).catch(err=>{
                    alert("用戶信息更新失敗!")
                });
            },
            findAll(){
                //發(fā)送axios請求
                axios.get("http://localhost:8990/users").then(res=>{
                    console.log(res.data);
                    this.users = res.data;
                }); //es6 箭頭函數(shù) 注意:箭頭函數(shù)內(nèi)部沒有自己this  簡化 function(){} //存在自己this
            }
        },

6、修改用戶信息

6.1、后端代碼

1、UserDAO

//更新用戶信息
void update(User user);

//基于id查詢用戶信息
User findById(Integer id);

2、UserDAOMapper.xml

<!--update-->
<update id="update" parameterType="User">
    update t_user
    set
    name = #{name},
    age = #{age},
    salary = #{salary},
    des = #{des}
    where id = #{id}
</update>

<!--findById-->
<select id="findById" parameterType="Integer" resultType="User">
    select
    id,name,age,salary,des
    from t_user
    where id = #{id}
</select>

3、service

UserService

//修改用戶信息
void update(User user);

//基于id查詢用戶信息
User findById(Integer id);

UserServiceImpl實現(xiàn)類

@Override
public void update(User user) {
    userDAO.update(user);
}

@Override
@Transactional(propagation = Propagation.SUPPORTS) //方法上聲明事務注解  Propagation:事務傳播屬性 支持事務
public User findById(Integer id) {
    return userDAO.findById(id);
}

4、control

在這里我們要根據(jù)前端請求的參數(shù)進行判斷。如果前端請求的參數(shù)中id為空,說明是添加操作,否則是更新操作,我們執(zhí)行相對應的代碼。

//添加員工信息接口
@PostMapping("saveOrUpdate")
public void saveOrUpdate(@RequestBody User user){
    log.info("接收的業(yè)務邏輯:{}",user);
    //判斷是否存在id
    //存在: 更新操作      不存在id: 添加操作
    if(StringUtils.isEmpty(user.getId())){ //如果為空
        log.info("添加業(yè)務邏輯......");
        userService.save(user);  //添加
    }else{
        log.info("更新業(yè)務邏輯......");
        userService.update(user);
    }

}

6.2、前端代碼

我們點擊修改按鈕,顯示用戶信息。

1、我們先給修改按鈕添加根據(jù)id查詢用戶信息事件

<a href="" class=" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" btn btn-info btn-sm" @click.prevent="userEditDetail(user.id)">修改</a>

2、userEditDetail(id)

userEditDetail(id){  //用來在表單中將當前點擊用戶信息進行回顯
    axios.get("http://localhost:8990/user/"+id).then(res=>{
        this.user = res.data;  //完成數(shù)據(jù)回顯
    });
},

3、給提交按鈕綁定修改或者添加用戶信息事件

<button type="button" class="btn btn-primary btn-block" @click="saveOrUpdate">提交</button>

4、saveOrUpdate()

saveOrUpdate(){ //保存或者修改方法
    if(!this.user.name){
        alert("姓名不能為空!");
        return ;
    }
    console.log(this.user);
    axios.post("http://localhost:8990/saveOrUpdate",this.user).then(res=>{
        this.user={}; //添加成功,清空數(shù)據(jù)
        alert("用戶信息更新成功!");
        //更新原始列表的數(shù)據(jù)
        this.findAll(); //調(diào)用查詢所有
    }).catch(err=>{
        alert("用戶信息更新失敗!")
    });
},
},
findAll(){
    //發(fā)送axios請求
    axios.get("http://localhost:8990/users").then(res=>{
        console.log(res.data);
        this.users = res.data;
    }); //es6 箭頭函數(shù) 注意:箭頭函數(shù)內(nèi)部沒有自己this  簡化 function(){} //存在自己this
},

7、刪除用戶信息

7.1、后端代碼

1、UserDAO接口

//基于id刪除用戶信息
void delete(Integer id);

2、UserDAOMapper.xml

<!--delete-->
<delete id="delete" parameterType="Integer">
    delete from t_user where id = #{id}
</delete>

3、service

UserService

//根據(jù)id刪除用戶信息
void delete(Integer id);

UserServiceImpl

@Override
public void delete(Integer id) {
    userDAO.delete(id);
}

4、controller

//根據(jù)id刪除用戶信息的接口
@DeleteMapping("delete/{id}")
public void delete(@PathVariable Integer id){
    userService.delete(id);
}

7.2、前端代碼

1、給刪除按鈕綁定刪除事件

<a href="javascript:;" rel="external nofollow"  class="btn btn-danger btn-sm" @click="delUser(user.id)">刪除</a>

2、delUser(id)刪除用戶方法

delUser(id){ //刪除用戶方法
    //友情提醒刪除
    if(window.confirm("您確定要刪除這條記錄嗎?")){
        axios.delete("http://localhost:8990/delete/"+id).then(res=>{
            alert("用戶信息刪除成功!");
            this.findAll(); 調(diào)用查詢所有
        }).catch(err=>{
            alert("用戶信息刪除失敗!");
        });
    }
}

以上就是“Vue怎么結合Springboot實現(xiàn)前后端分離”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI