SpringBoot+Vue+Axios+BootStrap實現圖書的增刪改查功能示例

由於是初學Vue、Axios,可能在界面和功能上存在著一些問題,但這些並不妨礙使用。如果有對編程感興趣的朋友,可以試著做一做。這個由於是第一次做,不太熟練。在後續的過程中會不斷的完善。

一、開發工具

IntelliJ IDEA Ultimate 2021.1

apache-maven-3.5.4

MySQL5.7

JDK 1.8.0_281

二、項目結構

在這裡插入圖片描述

三、編寫項目

1、創建數據庫

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for books
-- ----------------------------
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books`  (
  `bookId` int(0) NOT NULL AUTO_INCREMENT COMMENT '書id',
  `bookName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '書名',
  `bookCounts` int(0) NOT NULL COMMENT '數量',
  `detail` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '描述',
  PRIMARY KEY (`bookId`) USING BTREE,
  INDEX `bookID`(`bookId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of books
-- ----------------------------
INSERT INTO `books` VALUES (1, 'Java', 1, '從入門到放棄');
INSERT INTO `books` VALUES (2, 'MySQL', 10, '從刪庫到跑路');
INSERT INTO `books` VALUES (3, 'Linux', 5, '從進門到進牢');

SET FOREIGN_KEY_CHECKS = 1;

2、添加依賴

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.4.1</version>
    </dependency>
    <dependency>
        <groupId>org.webjars.bower</groupId>
        <artifactId>jquery</artifactId>
        <version>3.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.webjars.npm</groupId>
        <artifactId>vue</artifactId>
        <version>2.6.14</version>
    </dependency>
    <dependency>
        <groupId>org.webjars.npm</groupId>
        <artifactId>axios</artifactId>
        <version>0.20.0</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.78</version>
    </dependency>
</dependencies>

3、修改項目resources目錄下application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.pojo

4、在pojo包中編寫實體類

package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private Integer bookId;
    private String bookName;
    private Integer bookCounts;
    private String detail;
}

5、在java目錄下的mapper包中編寫接口類

package com.example.mapper;

import com.example.pojo.Book;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface BookMapper {

    List<Book> findAll();

    int addBook(Book book);

    int updateBook(Book book);

    int deleteBook(Integer bookId);

}

6、在resources目錄下的mapper中編寫mapper.xml文件

<?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.example.mapper.BookMapper">

    <resultMap id="bookMap" type="com.example.pojo.Book">
        <id column="bookId" property="bookId" javaType="Integer"/>
        <result column="bookName" property="bookName" javaType="String"/>
        <result column="bookCounts" property="bookCounts" javaType="Integer"/>
        <result column="detail" property="detail" javaType="String"/>
    </resultMap>

    <select id="findAll" resultMap="bookMap">
        select *
        from books
    </select>

    <insert id="addBook" parameterType="com.example.pojo.Book">
        insert into books (bookName, bookCounts, detail)
        values (#{bookName}, #{bookCounts}, #{detail});
    </insert>

    <update id="updateBook" parameterType="com.example.pojo.Book">
        update books
        set bookName=#{bookName},
            bookCounts=#{bookCounts},
            detail=#{detail}
        where bookId = #{bookId}
    </update>

    <delete id="deleteBook" parameterType="Integer">
        delete
        from books
        where bookId = #{bookId}
    </delete>

</mapper>

7、在service包中編寫接口

package com.example.service;

import com.example.pojo.Book;
import com.example.vo.ResultVO;
import java.util.List;

public interface BookService {

    List<Book> findAll();

    ResultVO addBook(Book book);

    ResultVO updateBook(Book book);

    int deleteBook(Integer bookId);
}

8、在service包下的impl包中編寫接口的實現類

package com.example.service.impl;

import com.example.mapper.BookMapper;
import com.example.pojo.Book;
import com.example.service.BookService;
import com.example.vo.ResultVO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Override
    public List<Book> findAll() {
        return bookMapper.findAll();
    }

    @Override
    public ResultVO addBook(Book book) {
        int i = bookMapper.addBook(book);
        if (i==1){
            return new ResultVO(10000,"success");
        }else {
            return new ResultVO(10001,"defeat");
        }
    }


    @Override
    public ResultVO updateBook(Book book) {
        int i = bookMapper.updateBook(book);
        if (i==1){
            return new ResultVO(10000,"success");
        }else {
            return new ResultVO(10001,"defeat");
        }
    }

    @Override
    public int deleteBook(Integer bookId) {
        return bookMapper.deleteBook(bookId);
    }

}

9、在controller包中編寫控制層實現的方法

package com.example.controller;

import com.example.pojo.Book;
import com.example.service.BookService;
import com.example.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@Controller
public class BookController {

    @Resource
    private BookService bookService;

    @RequestMapping("/bookAll")
    @ResponseBody
    public List<Book> bookAll(){
        List<Book> bookList = bookService.findAll();
        return bookList;
    }

    @PostMapping("/bookAdd")
    @ResponseBody
    public ResultVO addBook(@RequestBody Book book){
        ResultVO resultVO = bookService.addBook(book);
        return resultVO;
    }

    @PostMapping("/bookUpdate")
    @ResponseBody
    public ResultVO updateBook(@RequestBody Book book){
        return bookService.updateBook(book);
    }

    @GetMapping("/bookDelete/{bookId}")
    @ResponseBody
    public int deleteBook(@PathVariable("bookId") Integer bookId){
        return bookService.deleteBook(bookId);
    }

}

10、在vo包中編寫ResultVo

package com.example.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResultVO {

    //響應碼
    private int code;

    //提示消息
    private String msg;

    //響應數據
    private Object data;

    public ResultVO(int code,String msg){
        this.code=code;
        this.msg=msg;
    }
}

11、在webapp下創建list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>書籍列表</title>
    <!--1. 添加vue依賴-->
    <script src="/webjars/vue/2.6.14/dist/vue.min.js"></script>
    <!--2. 添加axios依賴-->
    <script src="/webjars/axios/0.20.0/dist/axios.min.js"></script>
    <!--3. 添加jquery依賴-->
    <script src="/webjars/jquery/3.6.0/dist/jquery.min.js"></script>
    <!--4. 添加bootstrap依賴-->
    <link rel="stylesheet" href="/webjars/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="/webjars/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <style>
        .table {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <div class="panel-title">
                <h3>書籍列表(SpringBoot+ Vue + Axios + BootStrap)</h3>
            </div>
        </div>
        <table class="table table-striped table-hover">
            <tr>
                <td>書籍編號</td>
                <td>書籍名稱</td>
                <td>書籍數量</td>
                <td>書籍描述</td>
                <td>操作</td>
            </tr>
            <tr v-for="bk in bookList">
                <td>{{bk.bookId}}</td>
                <td>{{bk.bookName}}</td>
                <td>{{bk.bookCounts}}</td>
                <td>{{bk.detail}}</td>
                <td>
                    <a href="#" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal"
                       @click="book=bk;title='修改書籍'">修改</a>
                    <a href="" class="btn btn-danger btn-sm" @click="delBook(bk.bookId)">刪除</a>
                </td>
            </tr>
        </table>
        <div class="panel-footer text-right">
            <a href="#" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal"
               @click="book={};title='添加書籍'">添加書籍</a>
        </div>

        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">{{title}}</h4>
                        --{{book}}
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" method="post">
                            <input type="hidden" v-model="book.bookId">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">書籍名稱:</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" v-model="book.bookName" placeholder="書籍名稱">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">書籍數量:</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" v-model="book.bookCounts" placeholder="書籍數量">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">書籍描述:</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" v-model="book.detail" placeholder="書籍描述">
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">關閉(C)</button>
                        <button type="button" class="btn btn-primary" @click="save()">保存(S)</button>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>
</body>
</html>
<script>
    let vs = new Vue({
        el: '.container',
        data: {
            bookList: [],
            book: {},
            title: '添加書籍',
        },
        created() {
            //查詢所有圖書信息
            this.findAllBooks();
        },
        methods: {
            //1、查詢全部圖書信息
            findAllBooks() {
                axios.get("/bookAll").then(data => {
                    this.bookList = data.data
                })
            },
            //2、保存圖書
            save() {
                //根據bkl.bookId是否有值,決定添加還是修改
                let url = "/bookAdd";
                if (this.book.bookId) {
                    url = "/bookUpdate";
                }
                //向後臺發送請求
                axios({
                    method:'post',
                    url:url,
                    data:JSON.stringify(this.book),
                    headers:{
                        'Content-type':'application/json'
                    }
                }).then(res=>{
                    if (res.data.code==10000){
                        this.findAllBooks();
                    }
                    $("#myModal").modal('hide');
                })
            },
            //3、刪除書籍
            delBook(bookId) {
                let url = "/bookDelete/"+bookId;
                if (confirm("你確定要刪除嗎?")) {
                    axios.get(url).then(function (res){
                        if (res.data.code===10000){
                            this.findAllBooks();
                        }
                    })
                }
            }
        }
    })
</script>

四、運行項目

訪問地址:

http://localhost:8080/list.html

展示頁:

在這裡插入圖片描述

添加頁面:

在這裡插入圖片描述

修改頁:

在這裡插入圖片描述

到此這篇關於SpringBoot+Vue+Axios+BootStrap實現圖書的增刪改查功能示例的文章就介紹到這瞭,更多相關SpringBoot 增刪改查內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: