初學SpringBoot,很多地方都不懂,所以完成這個走了不少彎路,連夜寫blog記錄,生怕天一亮全忘干凈了……
前端:Vue(2 or 3),IDE是VS code
后端:Spring Boot,IDE是IDEA
數(shù)據(jù)庫: MySQL
目前實現(xiàn)功能:前后端代碼分離,顯示數(shù)據(jù)庫表的數(shù)據(jù)
步驟
1.【創(chuàng)建vue項目】
終端輸入
vue ui
打開圖形化界面,創(chuàng)建一個Vue項目,具體步驟如下圖:
?
?
?
?
耐心等待。。。
?
創(chuàng)建完成后可以編譯運行,并確認項目是否能夠成功跑起來?
?
?關閉終端,進行下一步。
2.【編寫vue代碼】
vs code打開剛才創(chuàng)建的vue項目(vue開發(fā)相關插件要自行下載好哦)
?如上圖,在package.json中查看當前vue版本號,確定當前項目是vue2還是3!這個很重要!
接下來cmd+shift+Y打開終端,下載axios插件。
如果你是vue3,就輸入
npm install axios
如果是vue2,就輸
vue add axios
注:踩過的坑,使用如果是vue3使用vue add axios安裝,導致版本不一致,會出現(xiàn)這樣子的bug:export 'default' (imported as 'Vue') was not found in 'vue'?
?我的項目是vue3,所以
?執(zhí)行完畢后,在view中新建 BookView.vue視圖,這個的代碼先不急。
router中配置一個新的路由,將index.js修改代碼為:
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Book from '../views/BookView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
},
{
path:'/book',
component:Book
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
(注:上面這些代碼不管是vue2,還是和我一樣是vue3,都可以用)
3.【創(chuàng)建數(shù)據(jù)庫】
數(shù)據(jù)庫名sbdb,表名book。
CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`author` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
4.【創(chuàng)建springboot項目】
?
?
?下一步直接finish
沿著這個路徑找到application.properties,把它刪掉。
?在同樣的位置,新建一個file,名為application.yml,這里面是連接數(shù)據(jù)庫的信息,以下代碼需要修改改數(shù)據(jù)庫名和密碼哦?
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/sbdb?serverTimezone=UTC&characterEncoding=utf-8
username: root
password: 你的數(shù)據(jù)庫密碼
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
properties:
hibernate:
format_sql: true
server:
port: 8181
?src->main->java->com.example.sbtest下新建package,名為entity,里面新建一個類,名為Book。注意,這歌Book不是任取的,Book映射到數(shù)據(jù)庫中的book表(類名首字母小寫就是對應的表名)
package com.example.sbtest.entity;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Data
public class Book {
@Id
private Integer id;
private String name;
private String author;
}
?src->main->java->com.example.sbtest下新建package,名為repository,然后創(chuàng)建一個借口,名為BookRepository
package com.example.sbtest.repository;
import com.example.sbtest.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book,Integer> {
}
進行單元測試,驗證上面的類能否成功使用?
在接口上右鍵,如下圖,選擇Test
?
?可以發(fā)現(xiàn)test文件夾里自動生成一個測試類
?我們修改代碼,進行測試:
package com.example.sbtest.repository;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BookRepositoryTest {
@Autowired
private BookRepository bookRepository;
@Test
void findAll(){
System.out.println(bookRepository.findAll());
}
}
第一次運行需要稍等片刻。。。
查看結果:?
測試repository沒有問題后,我們就可以創(chuàng)建controller類,讓vue可以調(diào)用到后端的數(shù)據(jù)!
?src->main->java->com.example.sbtest下新建package,名為controller,然后創(chuàng)建一個接口,名為BookHandler
package com.example.sbtest.controller;
import com.example.sbtest.entity.Book;
import com.example.sbtest.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;
@RestController
@RequestMapping("/book")
public class BookHandler {
@Autowired
private BookRepository bookRepository;
@GetMapping("/findAll")
public List<Book> findAll(){
return bookRepository.findAll();
}
}
src->main->java->com.example.sbtest下新建package,名為config,然后創(chuàng)建一個接口,名為CrosConfig,這一步是為了解決跨域問題,可以簡單理解為前端的端口號訪問到后端的端口號:
package com.example.sbtest.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) {
/*
TODO bug: .allowedOrigins("*")改成 allowedOriginPatterns("*")
*/
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
5.啟動springboot項目
如圖,稍等片刻,運行完成后,打開瀏覽器輸入http://localhost:8181/book/findAll
順帶復制一下這個地址哦,項目別關,然后進入下一步!
6.【回到vue】
view中?BookView.vue視圖添加代碼:?
把你上一步復制的地址替換以下代碼axios.get()里的url,如果你和我的設置都是一樣的,就可以省去這一步。
<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>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:"Book",
data(){
return {
books:[]
}
},
created(){
const _this = this
axios.get( 'http://localhost:8181/book/findAll').then(function(resp){
///console.log(resp.data)
_this.books = resp.data
})
}
}
</script>
<style scoped>
</style>
至此,代碼部分徹底完工!最后,只要在vs code讓項目跑起來,在
http://localhost:8080/book就可以顯示后端的數(shù)據(jù)啦(注意IDEA也要保持項目運行哦)。文章來源:http://www.zghlxwxcb.cn/news/detail-861264.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-861264.html
?肝不動了,有講不清楚的地方歡迎在評論區(qū)指出,制作不易,歡迎點贊收藏哦(^_^)
到了這里,關于SpringBoot+Vue入門并實現(xiàn)前后端分離和數(shù)據(jù)庫查詢(入門筆記超詳細)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!