天天看點

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

目錄

    • 使用者清單頁面開發
    • 項目介紹
    • 1、前端html頁面編寫
    • 2、springboot架構搭建
      • 2.1、項目建立
      • 2.2、連接配接資料庫
      • 2.3、項目完整依賴
    • 3、編寫entity層
    • 4、查詢使用者資訊
      • 4.1、後端代碼編寫
      • 4.2、前端代碼編寫
    • 5、添加使用者資訊
      • 5.1、後端代碼編寫
      • 5.2、前端代碼編寫
    • 6、修改使用者資訊
      • 6.1、後端代碼
      • 6.2、前端代碼
    • 7、删除使用者資訊
      • 7.1、後端代碼
      • 7.2、前端代碼

使用者清單頁面開發

項目介紹

使用者清單頁面開發,可以實作簡單的查詢,删除,修改,和添加使用者資訊功能。前端使用vue架構,後端使用springboot架構,一個簡單的vue+springboot前後端分離小項目。

本項目主要子產品及技術點如圖

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

1、前端html頁面編寫

頁面:

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

代碼:

<!DOCTYPE html>
<html lang="en">
<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">
</head>
<body>
    <div id="app">

        <div class="container-fluid">
            <!--标題行-->
            <div class="row">
                <div class="col-sm-6 col-sm-offset-3"><h1 class="text-center">使用者清單</h1></div>
            </div>
            <!--資料行-->
            <div class="row">
                <div class="col-sm-10 col-sm-offset-1">
                    <!--添加按鈕-->
                    <a href="" class="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="btn btn-danger btn-sm">删除</a>
                                <a href="" class="btn btn-info btn-sm">修改</a>
                            </td>
                        </tr>

                    </table>
                    <!--添加 和 修改表單-->
                    <form>
                        <div class="form-group">
                            <label class="control-label">編号</label>
                            <div >
                                <p class="form-control-static">0001</p>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="name">姓名</label>
                            <input type="text" class="form-control" id="name" placeholder="請輸入姓名">
                        </div>
                        <div class="form-group">
                            <label for="salary">工資</label>
                            <input type="text" class="form-control" id="salary" placeholder="請輸入工資">
                        </div>
                        <div class="form-group">
                            <label for="age">年齡</label>
                            <input type="text" class="form-control" id="age" placeholder="請輸入年齡">
                        </div>
                        <div class="form-group">
                            <label for="description">個人簡介</label>
                            <input type="text" class="form-control" 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(){
            //發送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 實作使用者清單單頁面開發(建議收藏)

js目錄下存放vue和axios資源檔案。

2、springboot架構搭建

2.1、項目建立

1、建立

maven

項目,取名為

vue_day3_admin

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

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 實作使用者清單單頁面開發(建議收藏)

2.2、連接配接資料庫

1、建立

vue_day3

資料庫

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、引入資料庫相關依賴

<!--整合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出現的位置
mybatis.mapper-locations=classpath:com/xiao/mapper/*.xml
mybatis.type-aliases-package=com.xiao.entity

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

           

4、

springboot

連接配接

mysql

資料庫

  • 4.1、打開Data Sources and Deivers 輸入資料庫user和password,并選擇要連接配接的資料庫。
前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)
  • 4.2、設定時區為UTC
    前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

5、啟動測試一下

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

沒有任何問題。

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層

建立

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

下建立如下目錄

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

代碼:

<?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

實作類

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 //代表這是一個業務層元件 作用:用來在spring工廠中建立一個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 實作使用者清單單頁面開發(建議收藏)

BasicTest

TestUserService

測試成功!!!

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

4.2、前端代碼編寫

1、在

created()

函數中添加

axios

請求

# 生命周期鈎子:生命周期函數
            初始化階段
            1.beforeCreate vue執行個體自身事件生命周期初始化
            2.created 完成自定義data methods computed 注入和校驗    推薦
            3.beforeMount将el指向html編譯為模闆,并沒有完成模闆注入
            4.Mounted将編譯模闆進行資料注入,并将注入完成模闆形成虛拟dom替換el指向原始dom
           

代碼:

var app = new Vue({
    el: "#app",
    data:{
        msg:"vue 生命周期",
        users:[], //定義一個users空數組,用來存貯所有使用者的資訊
    },
    methods:{

    },
    computed:{

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

2、測試

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

測試成功!!!

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

自增長序列,新插入一條資料時,怎麼得到主鍵?

加入以下屬性即可:

useGeneratedKeys=“true” keyProperty=“id”

useGeneratedKeys 取值範圍true、false 預設值是:false。 含義:設定是否使用JDBC的getGenereatedKeys方法擷取主鍵并指派到keyProperty設定的領域模型屬性中。

keyProperty 取id的key值,主要是在主鍵是自增的情況下,添加成功後可以直接使用主鍵值,其中keyProperty的值是對象的屬性值,不是資料庫表中的字段名。

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 class="form-group">
    <label for="name">姓名</label>
    <input type="text" class="form-control" v-model="user.name" id="name" placeholder="請輸入姓名">
</div>
<div class="form-group">
    <label for="salary">工資</label>
    <input type="text" class="form-control" v-model="user.salary" id="salary" placeholder="請輸入工資">
</div>
<div class="form-group">
    <label for="age">年齡</label>
    <input type="text" class="form-control" v-model="user.age" id="age" placeholder="請輸入年齡">
</div>
<div class="form-group">
    <label for="description">個人簡介</label>
    <input type="text" class="form-control" 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空數組,用來存貯所有使用者的資訊
            user:{},  //定義了一個空的json對象
        },
        methods:{
            saveOrUpdate(){ //儲存或者修改方法
                //發送添加的請求
                console.log(this.user);
                axios.post("http://localhost:8990/saveOrUpdate",this.user).then(res=>{
                    this.user={}; //添加成功,清空資料
                    alert('使用者資訊更新成功!');
                    //更新原始清單的資料
                    this.findAll(); //調用查詢所有
                }).catch(err=>{
                    alert('使用者資訊更新失敗!')
                });
            },
            findAll(){
                //發送axios請求
                axios.get("http://localhost:8990/users").then(res=>{
                    console.log(res.data);
                    this.users = res.data;
                }); //es6 箭頭函數 注意:箭頭函數内部沒有自己this  簡化 function(){} //存在自己this
            }
        },
           

3、測試一下

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

測試成功!!!

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

實作類

@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

在這裡我們要根據前端請求的參數進行判斷。如果前端請求的參數中

id

為空,說明是添加操作,否則是更新操作,我們執行相對應的代碼。

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

}
           

6.2、前端代碼

我們點選修改按鈕,顯示使用者資訊。

1、我們先給修改按鈕添加根據id查詢使用者資訊事件

2、

userEditDetail(id)

userEditDetail(id){  //用來在表單中将目前點選使用者資訊進行回顯
    axios.get("http://localhost:8990/user/"+id).then(res=>{
        this.user = res.data;  //完成資料回顯
    });
},
           

3、給送出按鈕綁定修改或者添加使用者資訊事件

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={}; //添加成功,清空資料
        alert('使用者資訊更新成功!');
        //更新原始清單的資料
        this.findAll(); //調用查詢所有
    }).catch(err=>{
        alert('使用者資訊更新失敗!')
    });
},
},
findAll(){
    //發送axios請求
    axios.get("http://localhost:8990/users").then(res=>{
        console.log(res.data);
        this.users = res.data;
    }); //es6 箭頭函數 注意:箭頭函數内部沒有自己this  簡化 function(){} //存在自己this
},
           

5、測試一下

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

測試成功!!!

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

//根據id删除使用者資訊
void delete(Integer id);
           

UserServiceImpl

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

4、

controller

//根據id删除使用者資訊的接口
@DeleteMapping("delete/{id}")
public void delete(@PathVariable Integer id){
    userService.delete(id);
}
           

7.2、前端代碼

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

2、

delUser(id)

删除使用者方法

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

3、測試一下

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)

删除資訊成功!!!

至此,一個簡單的前後端分離小項目我們就完成了,需要源碼和筆記的可以私信我。

前後端分離 Vue + Springboot 實作使用者清單單頁面開發(建議收藏)