1. 程式人生 > 實用技巧 >springBoot+vue初始化前後端分離專案搭建(含資料庫)

springBoot+vue初始化前後端分離專案搭建(含資料庫)

所學材料資料庫資源

CREATE TABLE `book` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `author` varchar(20) DEFAULT NULL,
  `publish` varchar(20) DEFAULT NULL,
  `pages` int(10) DEFAULT NULL,
  `price` float(10,2) DEFAULT NULL,
  `bookcaseid` int(10) DEFAULT NULL,
  `abled` int(10) DEFAULT
NULL, PRIMARY KEY (`id`), KEY `FK_ieh6qsxp6q7oydadktc9oc8t2` (`bookcaseid`), CONSTRAINT `FK_ieh6qsxp6q7oydadktc9oc8t2` FOREIGN KEY (`bookcaseid`) REFERENCES `bookcase` (`id`) ) INSERT INTO `book` VALUES (1,'解憂雜貨店','東野圭吾','電子工業出版社',102,27.30,9,1),(2,'追風箏的人','卡勒德·胡賽尼','中信出版社',330,26.00,1,1),(3
,'人間失格','太宰治','作家出版社',150,17.30,1,1),(4,'這就是二十四節氣','高春香','電子工業出版社',220,59.00,3,1),(5,'白夜行','東野圭吾','南海出版公司',300,27.30,4,1),(6,'擺渡人','克萊兒·麥克福爾','百花洲文藝出版社',225,22.80,1,1),(7,'暖暖心繪本','米攔弗特畢','湖南少兒出版社',168,131.60,5,1),(8,'天才在左瘋子在右','高銘','北京聯合出版公司',330,27.50,6,1),(9,'我們仨','楊絳','生活.讀書.新知三聯書店',89,17.20,7,1),(10,'活著
','餘華','作家出版社',100,100.00,6,1),(11,'水滸傳','施耐庵','三聯出版社',300,50.00,1,1),(12,'三國演義','羅貫中','三聯出版社',300,50.00,2,1),(13,'紅樓夢','曹雪芹','三聯出版社',300,50.00,5,1),(14,'西遊記','吳承恩','三聯出版社',300,60.00,3,1);

vue前端配置

檢視需要安裝好nodejs和npm,然後輸入下面的cmd命令檢視是否安裝好

(我看到一篇部落格上說nodejs於vue相當於jvm於java,我不知道這個比喻是不是恰當)

版本出現,說明已經安裝好了,

還有一個vue-cli,vue腳手架 我之前已經安裝好了,下面的命名行

進入我們的工作目錄,使用腳手架安裝專案

出現命令,參考

完成後效果

執行專案 npm run dev

瀏覽器開啟:localhost:8080,即可看到vue專案

vue目錄

這個圖挺不錯的,講述vue入口,啟動的順序

資料展示頁面 可以與後端互動

在src下的components建立Book.vue

<template>
  <div>
      <table>
        <tr>
            <td>編號</td>
            <td>圖書名稱</td>
            <td>作者</td>
        </tr>
    </table>
    {{msg}}
  </div>
</template>

<script>
    export default {
        name: "book",
        data(){
          return{
            msg:'Hello Vue'
          }
        }
    }
</script>

<style scoped>

</style>

配置路由訪問book

瀏覽器輸入顯示

book.vue加強

<template>
  <div>
      <table>
        <tr>
            <td>編號</td>
            <td>圖書名稱</td>
            <td>作者</td>
        </tr>
        <tr v-for="item in books">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.author}}</td>
        </tr>
    </table>
    {{msg}}
  </div>
</template>

<script>
    export default {
        name: "book",
        data(){
          return{
            msg:'Hello Vue',
            books:[
              {
                  id: 1,
                  name:'Java零基礎實戰',
                  author:'寧楠'
              },
              {
                  id: 2,
                  name:'Vue零基礎實戰',
                  author:'張三'
              },
              {
                  id: 3,
                  name:'Spring Boot零基礎實戰',
                  author:'小明'
              }
            ]
          }
        }
    }
</script>

<style scoped>

</style>

建立後端springBoot應用

快速構建springBoot專案

勾選以上幾條,快速構建完成

配置application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name:  com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true
server:
  port: 8181

然後建立實體類

上面應該大寫

package com.southwind.springboottest.entity;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * @author
 * @create-date 2020/9/1 0001 15:23
 */

@Entity
@Data
public class Book {
    @Id
    private Integer id;
    private String name;
    private String author;
}

建立BookReposipory 繼承 JpaReposipory

測試下JPA

package com.southwind.springboottest.repository;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author
 * @create-date 2020/9/1 0001 15:33
 */
@SpringBootTest //首先加一個這樣一個註解
class BookRepositoryTest {

    @Autowired
    private BookRepository bookRepository;//測試需要注入

    @Test
    void findAll(){
        System.out.println(bookRepository.findAll());
    }
}

測試結果

寫controller層外部可以呼叫內部的sql語句

package com.southwind.springboottest.controller;

import com.southwind.springboottest.entity.Book;
import com.southwind.springboottest.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author
 * @create-date 2020/9/1 0001 15:51
 */
@RestController //全部基於rest
@RequestMapping("/book")
public class BookHandler {
    @Autowired
    private BookRepository bookRepository;

    @GetMapping("/findAll")
    public List<Book> findAll(){
        return bookRepository.findAll();
    }
}

前後端對接

安裝axios

在命令列內輸入
npm install axios -S
進行安裝。
安裝完成後在main.js中使用axios,在main.js中加入以下程式碼
import axios from 'axios'
Vue.prototype.$axios = axios book.vue加上傳送後端請求

<template>
  <div>
      <table>
        <tr>
            <td>編號</td>
            <td>圖書名稱</td>
            <td>作者</td>
        </tr>
        <tr v-for="item in books">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.author}}</td>
        </tr>
    </table>
    {{msg}}
  </div>
</template>

<script>
    export default {
        name: "book",
        data(){
          return{
            msg:'Hello Vue',
            books:[
              {
                  id: 1,
                  name:'Java零基礎實戰',
                  author:'寧楠'
              },
              {
                  id: 2,
                  name:'Vue零基礎實戰',
                  author:'張三'
              },
              {
                  id: 3,
                  name:'Spring Boot零基礎實戰',
                  author:'小明'
              }
            ]
          }
        },
        created(){
          this.$axios.get('http://localhost:8181/book/findAll').then(
            function(resp){
                console.log(resp);
            }
          )
        }
    }
</script>

<style scoped>

</style>

有跨域問題

後端配置CrosConfig

package com.southwind.springboottest.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author
 * @create-date 2020/9/1 0001 16:27
 */
@Configuration//自動配置
public class CrosConfig implements WebMvcConfigurer { //實現這個介面

    //重新addCorsMappings方法
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")      //新增對映路徑,“/**”表示對所有的路徑實行全域性跨域訪問許可權的設定
                .allowedOrigins("*")            //開放哪些ip、埠、域名的訪問許可權
                .allowedMethods( "GET", "POST", "PUT", "OPTIONS", "DELETE")        //開放哪些Http方法,允許跨域訪問
                .allowCredentials(true)         //是否允許傳送Cookie資訊
                .maxAge(3600)
                .allowedHeaders("*");            //允許HTTP請求中的攜帶哪些Header資訊
    }
}

介面顯示相關資料解決

然後response賦值過去

        created(){
          const _this = this;
          this.$axios.get('http://localhost:8181/book/findAll').then(
            function(resp){
                _this.books = resp.data;
            }
          )
        }

整體結果 呼叫資料庫