SpringBoot+Vue簡單前后端分離項(xiàng)目的增刪改查方式
SpringBoot 是提供一種快速整合的方式
前期準(zhǔn)備
新建數(shù)據(jù)庫
drop table if exists emp;
create table emp
(
empno int primary key auto_increment,
ename varchar(20),
job varchar(9),
hiredate date,
sal double
);
新建項(xiàng)目
新建SpringBoot項(xiàng)目,這里是第三種,項(xiàng)目建好后查看 main/java文件夾下的Application
@SpringBootApplication:主啟動類
相當(dāng)于@Configuration配置類、@EnableAutoConfiguration開啟自動配置、@CommponentScan 組件掃描(默認(rèn)掃描的是主啟動類所在包及子包)
在主啟動類中還需要在類的上面加兩個注解
@MapperScan("com.ssm.mapper") //mapper包的限定名
@EnableTransactionManagement //開啟事務(wù)管理
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
config 配置包
MvcConfig 類
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 跨域訪問設(shè)置
*/
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
.allowedHeaders("*")
.exposedHeaders("*");
}
}
application.yml
把application.properties重命名為:application.yml
server:
port: 1234 # 配置內(nèi)嵌Tomcat端口號
servlet:
context-path: /ssm # 配置應(yīng)用名
# 配置數(shù)據(jù)庫
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver # mysql驅(qū)動程序類名 8-com.mysql.cj.jdbc.Driver 5-com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: 123456
# 配置日志輸出級別
logging:
level:
# 項(xiàng)目包名
com.ssm: debug
# 配置mybatis實(shí)體類的別名包
mybatis:
type-aliases-package: com.ssm.po后端業(yè)務(wù)開發(fā)
po 類
@Data:默認(rèn)自動生成Getter、Setter、toString@AllArgsConstructor:默認(rèn)生成有參構(gòu)造方法(需要有參的時候兩個都加上)項(xiàng)目中默認(rèn)就有無參的@NoArgsConstructor:默認(rèn)生成無參構(gòu)造方法
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data // 默認(rèn)自動生成Getter、Setter、toString
// 需要有參的就加下面兩個注解,因?yàn)槟J(rèn)就有無參的
@AllArgsConstructor // 默認(rèn)生成有參構(gòu)造方法
@NoArgsConstructor // 默認(rèn)生成無參構(gòu)造方法
public class Emp {
private Integer empno;
private String ename;
private String job;
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
private Date hiredate;
private Double sal;
}
mapper 接口
增加和修改用的參數(shù)是實(shí)體類,刪除和 id 查詢用的是 int 主鍵
查詢所有數(shù)據(jù)用List
簡單語句寫注解里:
@Mapper
public interface EmpMapper {
// 主鍵自增,這里不用寫
@Insert("insert into emp (ename,job,hiredate,sal) values(#{ename},#{job},#{hiredate},#{sal})")
int insert(Emp emp);
@Delete("delete from emp where empno=#{no}")
int delete(int empno);
@Update("update emp set ename=#{ename},job=#{job},hiredate=#{hiredate},sal=#{sal} where empno=#{empno}")
int update(Emp emp);
// 查詢所有數(shù)據(jù)的時候,把所有屬性都寫出來
@Select("select empno,ename,job,hiredate,sal from emp")
List<Emp> queryAllEmps();
}
service 接口
public interface EmpService {
String insert(Emp emp);
String delete(int empno);
String update(Emp emp);
List<Emp> queryAllEmps();
}
service 實(shí)現(xiàn)類
@Service
public class EmpServiceImpl implements EmpService{
// 添加依賴注入的注解
@Autowired
// 依賴關(guān)系,service依賴mapper
private EmpMapper mapper;
@Override
public String insert(Emp emp) {
// 添加未實(shí)現(xiàn)的方法
return mapper.insert(emp)>0?"增加員工數(shù)據(jù)成功":"增加員工數(shù)據(jù)失敗";
}
@Override // int類型可以隨意起名,這里是主鍵方便區(qū)分
public String delete(int empno) {
return mapper.delete(empno)>0?"刪除員工數(shù)據(jù)成功":"刪除員工數(shù)據(jù)失敗";
}
@Override
public String update(Emp emp) {
return mapper.update(emp)>0?"修改員工數(shù)據(jù)成功":"修改員工數(shù)據(jù)失敗";
}
@Override
public List<Emp> queryAllEmps() {
return mapper.queryAllEmps();
}
}
controller 類
基于rest風(fēng)格
@RequestBody注解作用:提示SpringMVC框架客戶端發(fā)送的請求數(shù)據(jù)格式是JSON@PathVariable("主鍵")表示獲取請求路徑中的主鍵參數(shù),并將其綁定到方法的主鍵參數(shù)上。
@RestController
@RequestMapping("/emp")
public class EmpController {
@Autowired
// controller依賴service接口
private EmpService service;
@PostMapping
// @RequestBody注解作用:提示SpringMVC框架客戶端發(fā)送的請求數(shù)據(jù)格式是JSON
public String add(@RequestBody Emp emp) {
// 返回service處理的結(jié)果
return service.insert(emp);
}
@DeleteMapping("/{empno}")
public String delete(@PathVariable("empno")int empno) {
return service.delete(empno);
}
@PutMapping
public String update(@RequestBody Emp emp) {
return service.update(emp);
}
@GetMapping
public List<Emp> query(){
return service.queryAllEmps();
}
}
測試
在后端程序中右鍵主啟動類啟動 Spring Boot App
增加數(shù)據(jù)測試
POST請求

回到數(shù)據(jù)庫可以看到增加了一條數(shù)據(jù)
刪除數(shù)據(jù)測試
DELETE 方法,鏈接后面跟主鍵

回到數(shù)據(jù)庫可以看到 2號數(shù)據(jù)被刪除
修改數(shù)據(jù)測試
PUT 請求
Headers 里面的值不刪,在Body里面加上要修改的主鍵,及對應(yīng)要修改的數(shù)據(jù)

回到數(shù)據(jù)庫可以看到 1號數(shù)據(jù)被修改
查新數(shù)據(jù)測試
GET請求

前端頁面開發(fā)
vue新建項(xiàng)目后刪掉無用代碼
新建增加、修改、查詢視圖
接下來在 index.js 文件內(nèi)配置路由
import Query from '@/views/Query'
import Add from '@/views/Add'
import Update from '@/views/Update'
const routes = [
{
path:'/',
name:'query',
component:Query
},
{
path:'/add',
name:'add',
component:Add
},
{
path:'/update',
name:'update',
component:Update
}
]
查詢頁面
在查詢視圖中
- 看到按鈕就加上
@click=" " - 數(shù)據(jù)的表格要加
vfor指令和插值語法
<template>
<div>
<button @click="query">查詢</button>
<button @click="goAdd">增加</button>
<table>
<tr>
<th>員工編號</th>
<th>員工姓名</th>
<th>員工崗位</th>
<th>入職日期</th>
<th>員工工資</th>
<th>修改</th>
<th>刪除</th>
</tr>
<tr v-for="(item, index) in items" :key="index">
<th>{{ item.empno }}</th>
<th>{{ item.ename }}</th>
<th>{{ item.job }}</th>
<th>{{ item.hiredate }}</th>
<th>{{ item.sal }}</th>
<th><button @click="goUpdate(index)">修改</button></th>
<th><button @click="del(index)">刪除</button></th>
</tr>
</table>
</div>
</template>接下來現(xiàn)配數(shù)據(jù):vfor指令中的items
data () {
return {
items:[]
}
},
接下來重點(diǎn)是方法,差所有數(shù)據(jù),前后端要聯(lián)系起來,導(dǎo)入 Ajax 的庫axios
import axios from 'axios'
在methods內(nèi)配置查詢方法:
query(){
axios.get('http://localhost:1234/ssm/emp')
},
因?yàn)閯h除、增加、修改都要發(fā)請求,地址都是http://localhost:1234/ssm/emp,有點(diǎn)麻煩
接下來配置一個代理服務(wù)器,簡化路徑
在項(xiàng)目最后一個文件vue.config.js里面配置:
// 最后一行})前回車,前面代碼后加逗號
devServer: {
proxy:{
'/api':{
//target: 'http://localhost',
//target: 'http://localhost:端口號/后端文件名/'
target: 'http://localhost:1234/ssm/',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
以后再發(fā)請求這個路徑就可以被/api替代
路徑后面跟上.then(),里面加上箭頭函數(shù),里面寫響應(yīng)(resp),最后寫賦值
所以最后查詢視圖的路徑及代碼:
query(){
axios.get('/api/emp')
.then((resp)=> {
this.items = resp.data
})
},
啟動項(xiàng)目:點(diǎn)擊查詢

刪除功能
在查詢視圖內(nèi)
復(fù)制上面刪除按鈕中的方法,加在methods方法內(nèi):
直接發(fā)請求
// i代表數(shù)組下標(biāo)
del(i){
axios.delete(`/api/emp/${this.items[i].empno}`)
.then( (resp)=>{
alert(resp.data)
// 刪完后查詢一下
this.query()
})
},

添加頁面
首先在首頁視圖中加上添加的方法,以便跳轉(zhuǎn)
不需要傳參,只需要跳轉(zhuǎn)的路徑
goAdd(){
this.$router.push('/add')
},
這時候可以跳轉(zhuǎn),但是大白屏
在添加視圖內(nèi)
<template>
<div>
員工姓名:<input type="text" v-model="emp.ename">
員工崗位:<input type="text" v-model="emp.job">
入職日期:<input type="date" v-model="emp.hiredate">
員工工資:<input type="number" v-model="emp.sal">
<button @click="add">提交</button>
</div>
</template>先導(dǎo)入axios
import axios from 'axios'
data數(shù)據(jù)中:
data () {
return {
emp:{
ename: '',
job: '',
hiredate: '',
sal: ''
}
}
},
最后添加methods方法
methods: {
add(){
// 增加post請求,方法里面兩個參,一個地址一個數(shù)據(jù)
axios.post('/api/emp',this.emp)
// 響應(yīng)
.then( (resp)=>{
// 彈窗
alert(resp.data)
})
}
},
在查詢頁面點(diǎn)擊添加:

修改頁面
在查詢視圖內(nèi)的methods方法內(nèi)加上修改方法
會話傳參方法:
goUpdate(i){
//起個名字,數(shù)組數(shù)據(jù)用JSON格式格式化一下
sessionStorage.setItem('emp',JSON.stringify(this.items[i]))
// 跳轉(zhuǎn)
this.$router.push('/update')
}
在修改視圖內(nèi):
修改代碼結(jié)構(gòu)基本和增加一樣,這里可以直接復(fù)制增加的代碼,然后修改部分代碼
修改的話需要指定編號,但是編號不能被修改(設(shè)置只讀)
<input type="text" v-model="emp.empno" readonly> <br>
然后修改按鈕的方法名
<button @click="update">修改</button>
修改的話要把之前會話的數(shù)據(jù)從鉤子函數(shù)中取出來
mounted () {
// 按照名字取出數(shù)據(jù)
let s = sessionStorage.getItem('emp')
// 恢復(fù)成對象形式,再賦值給emp表
this.emp = JSON.parse(s)
}
methods方法里面的修改方法名(update)和請求類型需要改(put)
methods: {
update(){
axios.put('/api/emp',this.emp)
.then( (resp)=>{
alert(resp.data)
})
}
},
最后修改視圖的完整代碼:
<template>
<div>
<input type="text" v-model="emp.empno" readonly> <br>
<input type="text" v-model="emp.ename"> <br>
<input type="text" v-model="emp.job"> <br>
<input type="date" v-model="emp.hiredate"> <br>
<input type="number" v-model="emp.sal"> <br>
<button @click="update">修改</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
emp:{
ename: '',
job: '',
hiredate: '',
sal: ''
}
}
},
methods: {
update(){
axios.put('/api/emp',this.emp)
.then( (resp)=>{
alert(resp.data)
})
}
},
components: {},
computed: {},
watch: {},
mounted () {
// 取出數(shù)據(jù)
let s = sessionStorage.getItem('emp')
this.emp = JSON.parse(s)
}
}
</script>
<style scoped>
</style>

總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
- SpringBoot+Vue 前后端接口交互的項(xiàng)目實(shí)踐
- Vue3+Springboot實(shí)現(xiàn)前后端防抖增強(qiáng)的示例代碼
- 如何利用SpringBoot與Vue3構(gòu)建前后端分離項(xiàng)目
- springboot+vue前后端分離項(xiàng)目中使用jwt實(shí)現(xiàn)登錄認(rèn)證
- springboot和vue前后端交互的實(shí)現(xiàn)示例
- SpringBoot+Vue前后端分離實(shí)現(xiàn)審核功能的示例
- 基于SpringBoot+vue實(shí)現(xiàn)前后端數(shù)據(jù)加解密
相關(guān)文章
Java?9中List.of()的使用示例及注意事項(xiàng)
Java 9引入了一個新的靜態(tài)工廠方法List.of(),用于創(chuàng)建不可變的列表對象,這篇文章主要介紹了Java?9中List.of()的使用示例及注意事項(xiàng)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-03-03
Java 高并發(fā)十: JDK8對并發(fā)的新支持詳解
本文主要介紹Java 高并發(fā)JDK8的支持,這里整理了詳細(xì)的資料及1. LongAdder 2. CompletableFuture 3. StampedLock的介紹,有興趣的小伙伴可以參考下2016-09-09
Java設(shè)計模式之備忘錄模式(Memento模式)介紹
這篇文章主要介紹了Java設(shè)計模式之備忘錄模式(Memento模式)介紹,memento是一個保存另外一個對象內(nèi)部狀態(tài)拷貝的對象,這樣以后就可以將該對象恢復(fù)到原先保存的狀態(tài),需要的朋友可以參考下2015-03-03
SpringBoot實(shí)現(xiàn)接口的各種參數(shù)校驗(yàn)的示例
本文主要介紹了SpringBoot實(shí)現(xiàn)接口的各種參數(shù)校驗(yàn)的示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
基于Spring AOP proxyTargetClass的行為表現(xiàn)總結(jié)
這篇文章主要介紹了Spring AOP proxyTargetClass的行為表現(xiàn)總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java實(shí)現(xiàn)滑動驗(yàn)證碼的示例代碼
這篇文章主要為大家介紹了如何用Java語言實(shí)現(xiàn)滑動驗(yàn)證碼的生成,項(xiàng)目采用了springboot,maven等技術(shù),感興趣的小伙伴可以跟隨小編學(xué)習(xí)一下2022-02-02

