上一篇:前后端分離初體驗一:前端環境搭建
參考:https://www.bilibili.com/video/BV137411B7vB
B站UP:楠哥教你學Java
框架:vue + springboot
項目已上傳至GitHub:
前端:https://github.com/ownzyuan/vuetest_01
后端:https://github.com/ownzyuan/springboot_vue_test_01/tree/master
創建SpringBoot項目
為方便測試,使用了 jpa 和 lombok
配置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
導入數據庫+實體類
Book
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 / BookRepository
繼承 JpaRepository, 其中泛型 < Book, Integer>,Book是實體類,Integer是主鍵類型
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客戶端
特點
-
自動轉換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; }) }
成功輸出到頁面上