1.@PostMapping請求實現添加
在實現添加時,前臺一般會傳一個json對象給後臺,這個對象不能直接使用,需要進行轉化,使用@RequestBody
註解即可實現。
其中@RequestBody
的常用方式如下鏈接:
@RequestBody註解常見的使用場景和使用方式
addPost() {
if (this.post.name == null || this.post.name == "") {
this.$message.error('職位不能爲空!');
} else {
this.postRequest("/system/basic/post/addPost", this.post).then(resp => {
if (resp) {
this.initPost();
this.post.name = "";
}
})
}
}
@PostMapping("/addPost")
public RespBean addPosition(@RequestBody Position position) {
int num = positionService.addPosition(position);
if (num == 1) {
return RespBean.ok("添加成功!");
} else {
return RespBean.error("添加失敗!");
}
}
2.@PutMapping請求實現修改
修改操作時,json對象的轉化是一樣的,同post請求,使用@RequestBody
註解。
doEditPost() {
this.putRequest("/system/basic/post/editPost", this.editPost).then(resp => {
if (resp) {
this.dialogFormVisible = false;
this.initPost();
}
})
}
@PutMapping("/editPost")
public RespBean editPostById(@RequestBody Position position) {
if (positionService.editPostById(position) == 1) {
return RespBean.ok("修改成功!");
} else {
return RespBean.error("修改失敗!");
}
}
3.1 DeleteMapping請求實現單點刪除
實現刪除操作一般需要一個id即可,此時可以在url上將id傳到後臺即可,不需要通過json的形式傳值。後臺接收使用@PathVariable
註解。
handleDelete(index, data) {
this.$confirm('此操作將永久刪除[' + data.name + ']職位, 是否繼續?', '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.deleteRequest("/system/basic/post/" + data.id).then(resp => {
if (resp) {
this.initPost()
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消刪除'
});
});
}
@DeleteMapping("/{id}")
public RespBean deletePostById(@PathVariable Integer id) {
int num = positionService.deletePostById(id);
if (num == 1) {
return RespBean.ok("刪除成功!");
} else {
return RespBean.error("刪除失敗!");
}
}
3.2 DeleteMapping請求實現批量刪除
實現批量刪除需要獲得要刪除記錄的所有id,可以存放在數組中。
前臺可以直接封裝一個id數組傳到後臺,在數據庫進行批量操作。
//批量刪除前臺
handleManyDelete() {
this.$confirm('此操作將永久刪除[' + this.multipleSelection.length + ']條記錄, 是否繼續?', '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//單引號表示變量
let ids = '?';
this.multipleSelection.forEach(item=>{
ids+='ids='+item.id+'&';
})
this.deleteRequest("/system/basic/post/many" + ids).then(resp => {
if (resp) {
this.initPost()
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消刪除'
});
});
}
//批量刪除後臺控制層
@DeleteMapping("/many")
public RespBean deleteManyPost(Integer[] ids) {
if (positionService.deleteManyPost(ids) == ids.length) {
return RespBean.ok("批量刪除成功!");
} else {
return RespBean.error("批量刪除失敗!");
}
}
//批量刪除數據庫操作,使用的mybatis。
<delete id="deleteManyPost">
delete from position
where id in (
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>)
</delete>