先後端分離初體驗二:後端環境搭建+數據交互

上一篇:先後端分離初體驗一:前端環境搭建html

 

參考:https://www.bilibili.com/video/BV137411B7vB前端

B站UP:楠哥教你學Javavue

 

框架:vue + springbootjava

 

後端

建立SpringBoot項目

  爲方便測試,使用了 jpa 和 lomboknode

 

配置application.yml

spring:
   datasource:
     #注意使用時區
     url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
     username: root
     password: 123456
     driver-class-name: com.mysql.cj.jdbc.Driver
   jpa:
     #打印Sql到控制檯
     show-sql: true
     properties:
       hibernate:
         #format_sql:格式化打印出來的sql,不會一行全顯示
         format_sql: true
 server:
   port: 8181

 

導入數據庫+實體類

 

Bookmysql

package com.zy.entity;
 ​
 import lombok.Data;
 ​
 import javax.persistence.Entity;
 import javax.persistence.Id;
 ​
 @Entity
 @Data
 public class Book {
 ​
     //指定id爲主鍵
     @Id
     private Integer id;
     private String name;
     private String author;
 ​
 }

 

測試操做數據庫

repository / BookRepositoryios

  繼承 JpaRepository, 其中泛型 < Book, Integer>,Book是實體類,Integer是主鍵類型web

package com.zy.repository;
 ​
 import com.zy.entity.Book;
 import org.springframework.data.jpa.repository.JpaRepository;
 ​
 public interface BookRepository extends JpaRepository<Book,Integer> {
 }

 

測試 

package com.zy.repository;
 ​
 import com.zy.entity.Book;
 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 ​
 import java.util.List;
 ​
 import static org.junit.jupiter.api.Assertions.*;
 @SpringBootTest
 class BookRepositoryTest {
 ​
     @Autowired
     private BookRepository bookRepository;
 ​
     @Test
     void testBook(){
         List<Book> bookList = bookRepository.findAll();
         bookList.forEach(System.out::println);
     }
 ​
 }

 

輸出到頁面上

package com.zy.controller;
 ​
 import com.zy.entity.Book;
 import com.zy.repository.BookRepository;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 ​
 import java.util.List;
 ​
 @ResponseBody
 @Controller
 @RequestMapping("/book")
 public class BookHandler {
 ​
     @Autowired
     private BookRepository bookRepository;
 ​
     @GetMapping("/findAll")
     public List<Book> findAll(){
         List<Book> bookList = bookRepository.findAll();
         return bookList;
     }
 }

交互

1.前端:axios

  基於promise用於瀏覽器和node.js的http客戶端spring

特色sql

  • 自動轉換JSON數據

  • 支持瀏覽器和node.js

  • 支持promise

  • 能攔截請求和響應

  • 能轉換請求和響應數據

  • 能取消請求

  • 瀏覽器端支持防止CSRF(跨站請求僞造)

 

安裝 axios

  Terminal 中輸入 vue add axios

安裝完成

 

2.後端:配置WebMvcConfig

package com.zy.config;
 ​
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.CorsRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 ​
 @Configuration
 public class CrosConfig implements WebMvcConfigurer {
     
     @Override
     public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/**")
                 .allowedOrigins("*")
                 .allowedMethods("GET","HEAD","POST","DELETE","OPTIONS")
                 .allowCredentials(true)
                 .maxAge(3600)
                 .allowedHeaders("*");
     }
     
 }

addCorsMappings 會與以後的攔截器發生衝突,但用於測試暫時使用

 

3.前端:配置Book.vue

created

  初始化操做,每當頁面被加載,就會使用裏面的方法

get( Url )

  請求類型,括號中寫對應url

then()

  回調,括號中能夠寫方法

<template>
     <div>
         <table>
             <tr>
                 <td>編號</td>
                 <td>書名</td>
                 <td>做者</td>
             </tr>
             <!--books:被遍歷的數組 ,item:每次遍歷的對象-->
             <tr v-for="item in books">
                 <td>{{item.id}}</td>
                 <td>{{item.name}}</td>
                 <td>{{item.author}}</td>
             </tr>
         </table>
     </div>
 </template><script>
     export default {
         name: "Book",
 ​
         data() {
             return {
                 msg: 'Hello',
                 books: []
             }
         },
         //初始化操做,每當頁面被加載,就會使用裏面的方法
         created(){
             //get(Url):請求類型,括號中寫對應url  then():回調,括號中能夠寫方法
             axios.get('http://localhost:8181/book/findAll').then(function (resp) {
                 console.log(resp)
             })
         }
 ​
     }
 </script><style scoped></style>

 

4.同時啓動測試

resp中已經能得到後端給的數據了

說明交互已經成功,就差輸出到頁面上

 

5.數據輸出到前端頁面上

改進Book.vue

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

 

測試:books未定義

  由於這個this是在回調中的this,因此沒法指向上面的books

自定義this

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

成功輸出到頁面上

相關文章
相關標籤/搜索