文章目录
六、商品服务-分类维护
1.查出所有分类信息
三级分类
三级分类对应的表
controller
service
serviceImpl
获取到数据
过滤器筛选一级标题
@RequestMapping("/list/tree")
//@RequiresPermissions("product:category:list")
public R list(){
List<CategoryEntity> entities = categoryService.listWithTree();
//过滤器 得到一级标题 parent_cid == 0
List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).collect(Collectors.toList());
return R.ok().put("data", level1Menus);
}
筛选子类
在CategoryEnity里添加子类的属性
/**
* 子分类
*/
@TableField(exist = false)//子类在数据库中不存在
private List<CategoryEntity> children;
2.配置网关路由和路径重写
(1).前端页面编写
启动前后端,在后台管理系统的 系统管理-> 菜单管理中 添加商品菜单及其分类
在moudles下新建product文件夹新建procuct.vue
成功
(2).修改路径,访问网关
测试验证码
登录时的验证码是请求renrnefast模块的,所以需要将renrenfast注册到注册中心中
注册成功
设置路由
(3).跨域
解决方法:
- nginx
- 配置响应头
在网关中配置允许跨域
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class MyCrosConfig {
@Bean
public CorsWebFilter CorsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 这里配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
进入成功
(4).商品路由设置
a.配置商品的路由
b.配置nacos命名空间
c.注册成功
我们将相应模块的配置放在相应的命名空间中 而服务注册放在public中
已经可以从后端获取到数据了,接下俩完善前端页面展示数据
(5).前端完善页面
<template>
<el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId">
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
Append
</el-button>
<el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
Delete
</el-button>
</span>
</span>
</el-tree>
</template>
<script>
export default {
data() {
return {
menus: [],
defaultProps: {
children: 'children',
label: 'name'
}
};
},
methods: {
getMenus() {
this.$http({
url: this.$http.adornUrl('/product/category/list/tree'),
method: 'get'
}).then(({ data }) => {
console.log("success:", data.data)
this.menus = data.data
})
},
append(data) {
const newChild = { id: id++, label: 'testtest', children: [] };
if (!data.children) {
this.$set(data, 'children', []);
}
data.children.push(newChild);
},
remove(node, data) {
const parent = node.parent;
const children = parent.data.children || parent.data;
const index = children.findIndex(d => d.id === data.id);
children.splice(index, 1);
},
},
created() {
this.getMenus();
}
};
</script>
<style scoped>
</style>
3.完善删除效果
自己写一个删除方法
逻辑删除 修改数据的展示状态码
这里建议根据你导入的mybatis-plus依赖版本去查看相应文档,不同版本,配置过程不大相同
在mybatis-plus官方文档有使用方法,有一说一,mybatis-plus这第一个大图给我看乐了,太逗了逻辑删除 | MyBatis-Plus
进行全局配置
前端代码完善
<template>
<el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId" :default-expanded-keys="expandedKey">
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
Append
</el-button>
<el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
Delete
</el-button>
</span>
</span>
</el-tree>
</template>
<script>
export default {
data() {
return {
menus: [],
expandedKey: [],
defaultProps: {
children: 'children',
label: 'name'
}
};
},
methods: {
getMenus() {
this.$http({
url: this.$http.adornUrl('/product/category/list/tree'),
method: 'get'
}).then(({ data }) => {
console.log("success:", data.data)
this.menus = data.data
})
},
append(data) {
const newChild = { id: id++, label: 'testtest', children: [] };
if (!data.children) {
this.$set(data, 'children', []);
}
data.children.push(newChild);
},
remove(node, data) {
var ids = [data.catId]
this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http({
url: this.$http.adornUrl('/product/category/delete'),
method: 'post',
data: this.$http.adornData(ids, false)
}).then(({ data }) => {
this.$message({
showClose: true,
message: '菜单删除成功',
type: 'success'
});
//刷新出新的菜单
this.getMenus();
//设置需要默认展开的菜单
this.expandedKey = [node.parent.data.catId]
});
}).catch(() => {
});
},
created() {
this.getMenus();
}
},
created() {
this.getMenus();
}
};
</script>
<style scoped>
</style>
4.完善新增效果
(1).弹出对话框
<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
append(data) {
this.dialogVisible = true;
},
(2).对话框内容设置表单
<el-form :model="form">
<el-form-item label="活动名称" :label-width="formLabelWidth">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="活动区域" :label-width="formLabelWidth">
<el-select v-model="form.region" placeholder="请选择活动区域">
<el-option label="区域一" value="shanghai"></el-option>
<el-option label="区域二" value="beijing"></el-option>
</el-select>
</el-form-item>
</el-form>
完善新增效果
<template>
<div>
<el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId"
:default-expanded-keys="expandedKey">
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
Append
</el-button>
<el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
Delete
</el-button>
</span>
</span>
</el-tree>
<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
<el-form :model="category">
<el-form-item label="分类名称">
<el-input v-model="category.name" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="addCategory">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
category: { name: "", parentCid: 0, catLevel: 0, showStatus: 1, sort: 0 },
dialogVisible: false,
menus: [],
expandedKey: [],
defaultProps: {
children: 'children',
label: 'name'
}
};
},
methods: {
getMenus() {
this.$http({
url: this.$http.adornUrl('/product/category/list/tree'),
method: 'get'
}).then(({ data }) => {
console.log("success:", data.data)
this.menus = data.data
})
},
append(data) {
this.dialogVisible = true;
this.category.parentCid = data.catId;
this.category.catLevel = data.catLevel * 1 + 1;
},
addCategory() {
console.log(this.category);
this.$http({
url: this.$http.adornUrl("/product/category/save"),
method: "post",
data: this.$http.adornData(this.category, false)
}).then(({ data }) => {
this.$message({
message:"菜单添加成功",
type: "success"
});
//关闭对话框
this.dialogVisible = false;
this.getMenus();
this.expandedKey = [this.category.parentCid]
});
},
remove(node, data) {
var ids = [data.catId]
this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http({
url: this.$http.adornUrl('/product/category/delete'),
method: 'post',
data: this.$http.adornData(ids, false)
}).then(({ data }) => {
this.$message({
showClose: true,
message: '菜单删除成功',
type: 'success'
});
//刷新出新的菜单
this.getMenus();
//设置需要默认展开的菜单
this.expandedKey = [node.parent.data.catId]
});
}).catch(() => {
});
},
created() {
this.getMenus();
}
},
created() {
this.getMenus();
}
};
</script>
<style scoped>
</style>
5.修改按钮添加
<el-button type="text" size="mini" @click="() => edit(data)">
Edit
</el-button>
<el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
<el-form :model="category">
<el-form-item label="分类名称">
<el-input v-model="category.name" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<el-form :model="category">
<el-form-item label="图标">
<el-input v-model="category.icon" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<el-form :model="category">
<el-form-item label="计量单位">
<el-input v-model="category.productUnit" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitData">确 定</el-button>
</span>
</el-dialog>
data() {
return {
title: "",
//根据点击append\edit判断对话框类型
dialogType:"",
//添加菜单id
category: { name: "", parentCid: 0, catLevel: 0, showStatus: 1, sort: 0, catId: null },
dialogVisible: false,
menus: [],
expandedKey: [],
defaultProps: {
children: 'children',
label: 'name'
}
};
},
edit(data) {
this.dialogVisible = true;
this.dialogType = "edit";
this.title = "修改分类";
//发送请求获取当前节点最新的数据
this.$http({
url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
method: 'get',
params: this.$http.adornParams({})
}).then(({ data }) => {
//请求成功,将真正的数据进行回显
console.log("要回显的数据:", data);
this.category.name = data.data.name;
this.category.catId = data.data.catId;
this.category.icon = data.data.icon;
this.category.productUnit = data.data.productUnit;
this.category.parentCid = data.data.parentCid;
});
},
append(data) {
this.dialogVisible = true;
this.dialogType = "add";
this.title = "添加分类";
this.dialogVisible = true;
this.category.parentCid = data.catId;
this.category.catLevel = data.catLevel * 1 + 1;
this.category.catId = null;
this.category.name = "";
this.category.icon = "";
this.category.productUnit = "";
this.category.sort = 0;
this.category.showStatus = 1;
},
submitData() {
if (this.dialogType == "add") {
this.addCategory();
}
if (this.dialogType == "edit") {
this.editCategory();
}
},
editCategory() {
var { catId, name, icon, productUnit } = this.category;
var data = { catId, name, icon, productUnit };
this.$http({
url: this.$http.adornUrl('/product/category/update'),
method: 'post',
data: this.$http.adornData(data, false)
}).then(({ data }) => {
this.$message({
message: "菜单修改成功",
type: "success",
});
this.dialogVisible = false;
this.getMenus();
this.expandedKey = [this.category.parentCid]
});
},
addCategory() {
console.log(this.category);
this.$http({
url: this.$http.adornUrl("/product/category/save"),
method: "post",
data: this.$http.adornData(this.category, false)
}).then(({ data }) => {
this.$message({
message: "菜单添加成功",
type: "success"
});
//关闭对话框
this.dialogVisible = false;
this.getMenus();
this.expandedKey = [this.category.parentCid]
});
},
修改成功
6.修改-拖拽效果&批量删除
<template>
<div>
<el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
<el-button v-if="draggable" @click="batchSave">批量保存</el-button>
<el-button type="danger" @click="batchDelete">批量删除</el-button>
<el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId"
:default-expanded-keys="expandedKey" :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop"
ref="menuTree">
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
Append
</el-button>
<el-button type="text" size="mini" @click="() => edit(data)">
Edit
</el-button>
<el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
Delete
</el-button>
</span>
</span>
</el-tree>
<el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
<el-form :model="category">
<el-form-item label="分类名称">
<el-input v-model="category.name" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<el-form :model="category">
<el-form-item label="图标">
<el-input v-model="category.icon" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<el-form :model="category">
<el-form-item label="计量单位">
<el-input v-model="category.productUnit" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitData">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
pCid: [],
draggable: false,
updateNodes: [],
maxLevel: 0,
title: "",
dialogType: "",
category: { name: "", parentCid: 0, catLevel: 0, showStatus: 1, sort: 0, catId: null, productUnit: "", icon: "" },
dialogVisible: false,
menus: [],
expandedKey: [],
defaultProps: {
children: 'children',
label: 'name'
}
};
},
methods: {
getMenus() {
this.$http({
url: this.$http.adornUrl('/product/category/list/tree'),
method: 'get'
}).then(({ data }) => {
console.log("success:", data.data)
this.menus = data.data
})
},
batchDelete() {
let catIds = [];
let checkedNodes = this.$refs.menuTree.getCheckedNodes();
console.log("被选中的元素", checkedNodes);
for (let i = 0; i < checkedNodes.length; i++) {
catIds.push(checkedNodes[i].catId);
}
this.$confirm(`是否批量删除【${catIds}】菜单?`, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
})
.then(() => {
this.$http({
url: this.$http.adornUrl("/product/category/delete"),
method: "post",
data: this.$http.adornData(catIds, false)
}).then(({ data }) => {
this.$message({
message: "菜单批量删除成功",
type: "success"
});
this.getMenus();
});
})
.catch(() => {});
},
batchSave() {
this.$http({
url: this.$http.adornUrl("/product/category/update/sort"),
method: "post",
data: this.$http.adornData(this.updateNodes, false)
}).then(({ data }) => {
this.$message({
message: "菜单顺序等修改成功",
type: "success"
});
//刷新出新的菜单
this.getMenus();
//设置需要默认展开的菜单
this.expandedKey = this.pCid;
this.updateNodes = [];
this.maxLevel = 0;
// this.pCid = 0;
});
},
handleDrop(draggingNode, dropNode, dropType, ev) {
console.log("handleDrop: ", draggingNode, dropNode, dropType);
//1、当前节点最新的父节点id
let pCid = 0;
let siblings = null;
if (dropType == "before" || dropType == "after") {
pCid =
dropNode.parent.data.catId == undefined
? 0
: dropNode.parent.data.catId;
siblings = dropNode.parent.childNodes;
} else {
pCid = dropNode.data.catId;
siblings = dropNode.childNodes;
}
this.pCid.push(pCid);
//2、当前拖拽节点的最新顺序,
for (let i = 0; i < siblings.length; i++) {
if (siblings[i].data.catId == draggingNode.data.catId) {
//如果遍历的是当前正在拖拽的节点
let catLevel = draggingNode.level;
if (siblings[i].level != draggingNode.level) {
//当前节点的层级发生变化
catLevel = siblings[i].level;
//修改他子节点的层级
this.updateChildNodeLevel(siblings[i]);
}
this.updateNodes.push({
catId: siblings[i].data.catId,
sort: i,
parentCid: pCid,
catLevel: catLevel
});
} else {
this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
}
}
//3、当前拖拽节点的最新层级
console.log("updateNodes", this.updateNodes);
},
updateChildNodeLevel(node) {
if (node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
var cNode = node.childNodes[i].data;
this.updateNodes.push({
catId: cNode.catId,
catLevel: node.childNodes[i].level
});
this.updateChildNodeLevel(node.childNodes[i]);
}
}
},
allowDrop(draggingNode, dropNode, type) {
//1、被拖动的当前节点以及所在的父节点总层数不能大于3
//1)、被拖动的当前节点总层数
console.log("allowDrop:", draggingNode, dropNode, type);
//
this.countNodeLevel(draggingNode);
//当前正在拖动的节点+父节点所在的深度不大于3即可
let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
console.log("深度:", deep);
// this.maxLevel
if (type == "inner") {
// console.log(
// `this.maxLevel:${this.maxLevel};draggingNode.data.catLevel:${draggingNode.data.catLevel};dropNode.level:${dropNode.level}`
// );
return deep + dropNode.level <= 3;
} else {
return deep + dropNode.parent.level <= 3;
}
},
countNodeLevel(node) {
//找到所有子节点,求出最大深度
if (node.childNodes != null && node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
if (node.childNodes[i].level > this.maxLevel) {
this.maxLevel = node.childNodes[i].level;
}
this.countNodeLevel(node.childNodes[i]);
}
}
},
edit(data) {
this.dialogVisible = true;
this.dialogType = "edit";
this.title = "修改分类";
//发送请求获取当前节点最新的数据
this.$http({
url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
method: 'get',
params: this.$http.adornParams({})
}).then(({ data }) => {
//请求成功,将真正的数据进行回显
console.log("要回显的数据:", data);
this.category.name = data.data.name;
this.category.catId = data.data.catId;
this.category.icon = data.data.icon;
this.category.productUnit = data.data.productUnit;
this.category.parentCid = data.data.parentCid;
});
},
append(data) {
this.dialogVisible = true;
this.dialogType = "add";
this.title = "添加分类";
this.dialogVisible = true;
this.category.parentCid = data.catId;
this.category.catLevel = data.catLevel * 1 + 1;
this.category.catId = null;
this.category.name = "";
this.category.icon = "";
this.category.productUnit = "";
this.category.sort = 0;
this.category.showStatus = 1;
},
submitData() {
if (this.dialogType == "add") {
this.addCategory();
}
if (this.dialogType == "edit") {
this.editCategory();
}
},
editCategory() {
var { catId, name, icon, productUnit } = this.category;
var data = { catId, name, icon, productUnit };
this.$http({
url: this.$http.adornUrl('/product/category/update'),
method: 'post',
data: this.$http.adornData(data, false)
}).then(({ data }) => {
this.$message({
message: "菜单修改成功",
type: "success",
});
this.dialogVisible = false;
this.getMenus();
this.expandedKey = [this.category.parentCid]
});
},
addCategory() {
console.log(this.category);
this.$http({
url: this.$http.adornUrl("/product/category/save"),
method: "post",
data: this.$http.adornData(this.category, false)
}).then(({ data }) => {
this.$message({
message: "菜单添加成功",
type: "success"
});
//关闭对话框
this.dialogVisible = false;
this.getMenus();
this.expandedKey = [this.category.parentCid]
});
},
remove(node, data) {
var ids = [data.catId]
this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http({
url: this.$http.adornUrl('/product/category/delete'),
method: 'post',
data: this.$http.adornData(ids, false)
}).then(({ data }) => {
this.$message({
showClose: true,
message: '菜单删除成功',
type: 'success'
});
//刷新出新的菜单
this.getMenus();
//设置需要默认展开的菜单
this.expandedKey = [node.parent.data.catId]
});
}).catch(() => {
});
},
created() {
this.getMenus();
}
},
created() {
this.getMenus();
}
};
</script>
<style scoped>
</style>
七、商品服务-品牌管理
1.新增品牌管理菜单
生成品牌管理
2.前端页面渲染
将之前逆向工程生成的前端代码的品牌页面相关的放到product文件夹下
在数据库中的备注会在逆向工程生成前端代码中生成表格字段
权限按钮展示
3.显示状态开关
<el-table-column
prop="showStatus"
header-align="center"
align="center"
label="显示状态">
<template slot-scope="scope">
<el-switch
v-model="scope.row.showStatus"
active-color="#13ce66"
inactive-color="#ff4949"
:active-value="1"
:inactive-value="0"
@change="updateBrandStatus(scope.row)">
</el-switch>
</template>
</el-table-column>
updateBrandStatus(data){
//只需要品牌id和品牌状态两个数据,进行解构剔除掉没用的数据
let {brandId,showStatus} = data;
this.$http({
url: this.$http.adornUrl('/product/brand/update'),
method: 'post',
data: this.$http.adornData({brandId,showStatus}, false)
}).then(({ data }) => {
this.$message({
type: "success",
message: "状态更新成功"
})
});
},
4.文件上传功能
(1).云存储的开通与使用
微服务分布式的项目中,无论浏览器发给哪个服务进行文件上传\下载,它要上传\下载的文件都统一存储在一个文件系统里
这里使用我的阿里云对象存储oss,oss不仅在本项目可以用到,还可以用来搭建图床,方便将本地笔记上传到博客。推荐一个项目创建一个bucket。
(2).上传功能
如何做到从项目的上传文件功能上传到阿里云oss呢?
- 普通上传方式 :浏览器—>模块代码(获取到图片的java流数据)—>oss 安全,但是还要经过我们自己项目的服务器,增大访问量
- 服务端签名后直传:浏览器(请求上传)---->服务器(根据阿里云的账号密码生成一个防伪的签名:包含访问阿里云的令牌已经上传的地址)—>oss
进行OSS各类操作前,您需要先安装Java SDK。本文提供了Java SDK的多种安装方式,请结合实际使用场景选用。
官方文档安装 (aliyun.com)
安装SDK到product模块
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
官方代码
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "exampledir/exampleobject.txt";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath= "D:\\localpath\\examplefile.txt";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
测试上传
####(3).Alibaba Cloud OSS阿里云对象存储服务(普通上传方式实现)
相较于上面那种方法,Alibaba Cloud有更好的整合OSS的方法
官方文档:spring-cloud-alibaba/README-zh.md at 2.2.x · alibaba/spring-cloud-alibaba (github.com)
引入aliyun-oss-spring-boot-starter,同时注释掉之前文件上传的SDK(笔者在使用官方的依赖时会找不到包,所以用了下面这个包)
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
区别于之前我们在业务代码中配置key、pwd、endpoint,这里直接在配置文件中配置
编写测试类
@Autowired
OSSClient ossClient;
@Test
public void testUpload(){
// 填写Bucket名称,例如examplebucket。
String bucketName = "guli-hot-rabbit";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "2784BDECC161173F24D3CD68E3764865.jpg";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath= "C:\\Users\\10418\\Desktop\\2784BDECC161173F24D3CD68E3764865.jpg";
// // 创建OSSClient实例。
// OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
System.out.println("=================================上传完成===================================");
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
- 引入 spring-cloud-starter-alicloud-oss 依赖
- 配置key、secret、endpoint
- 使用 OSSClient 进行相关操作
(4).OSS获取服务端签名上传
a.一些基本配置
创建一个整合各种第三方功能的微服务模块
将oss依赖放到third-party里
将 common 里的依赖管理复制一份到 third-party 里
third-party 注册到nacos 配置
新建一个命名空间给third-party
因为common里引入了mybatis依赖,所以在third-party里我们要将其排除
需要注意的是,尽管我们在pom里排除了mybatis依赖,但是可能其他导入的包会包含mysql相关的依赖
所以我们直接在启动类上配置@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)去除掉数据源相关的配置
b.服务端签名后直传
OssController
package com.henu.soft.merist.thirdparty.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.sun.xml.internal.ws.api.FeatureListValidatorAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
public class OssController {
@Autowired
OSS ossClient;
@Value("${oss.bucket}")
private String bucket;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@Value("${spring.cloud.alicloud.oss.endpoint")
private String endpoint;
@RequestMapping("/oss/policy")
public Map<String,String> getPolicy(){
// // 填写Bucket名称,例如examplebucket。
// String bucket = "guli-hot-rabbit";
// 填写Host地址,格式为https://bucketname.endpoint。
String host = "https://" + bucket + "." + endpoint;
// // 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
// String callbackUrl = "https://192.168.0.0:8888";
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
String dir = format + "/";
Map<String, String> respMap = null;
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
respMap = new LinkedHashMap<String, String>();
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));\
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return respMap;
}
}
网关配置路由
通过网关访问
(5).前端页面修改
将封装好的文件添加
修改单文件、多文件上传的路径,为我们bucket的外网访问域名
导入单文件上传组件
<el-form-item label="品牌logo地址" prop="logo">
<!-- <el-input v-model="dataForm.logo" placeholder="品牌logo地址"></el-input> -->
<SingleUpload v-model="dataForm.logo"></SingleUpload>
</el-form-item>
components: { SingleUpload }
后端返回数据包装到data里
测试
产生跨域问题
阿里云设置跨域规则
logo地址变成了图片地址
提交表单的时候一直报400错误
可能会发生400错误的请求错误,因为请求中有一个简单的错误。 也许您输入了错误的URL,并且服务器由于某种原因无法返回404错误。 也许您的Web浏览器正在尝试使用过期或无效的cookie 。 在某些情况下,某些未正确配置的服务器也可能引发400错误,而不是更多有用的错误。 例如,当您尝试上传对某些站点太大的文件时,可能会显示400错误,而不是让您知道最大文件大小的错误。
因为我们的logo也就是图片地址太长了,只要修改数据库logo字段的数据类型为text大文本即可。
表单显示图片
<el-table-column prop="logo" header-align="center" align="center" label="品牌logo地址">
<template slot-scope="scope">
<img :src="scope.row.logo" style="width: 100px; height: 80px"/>
</template>
</el-table-column>
5.表单校验&自定义校验器
(1).前端校验
<el-form-item label="显示状态" prop="showStatus">
<el-switch v-model="dataForm.showStatus" active-color="#13ce66" inactive-color="#ff4949"
:active-value="1" :inactive-value="0">
</el-switch>
</el-form-item>
<el-form-item label="检索首字母" prop="firstLetter">
<el-input v-model="dataForm.firstLetter" placeholder="检索首字母"></el-input>
</el-form-item>
<el-form-item label="排序" prop="sort">
<el-input v-model.number="dataForm.sort" placeholder="排序"></el-input>
</el-form-item>
dataRule: {
name: [
{ required: true, message: "品牌名不能为空", trigger: "blur" }
],
logo: [
{ required: true, message: "品牌logo地址不能为空", trigger: "blur" }
],
descript: [
{ required: true, message: "介绍不能为空", trigger: "blur" }
],
showStatus: [
{ required: true, message: "显示状态[0-不显示;1-显示]不能为空", trigger: "blur" }
],
firstLetter: [
{
validator: (rule, value, callback) => {
if (value == '') {
callback(new Error('首字母必须填写'));
} else if (!/^[a-zA-Z]$/.test(value)){
callback(new Error('首字母必须a-z或者A-Z之间'));
}else{
callback();
}
}, trigger: "blur"
}
],
sort: [
{
validator: (rule, value, callback) => {
if (value == '') {
callback(new Error('排序字段必须填写'));
} else if (!Number.isInteger(value) || value<0){
callback(new Error('排序必须是一个大于等于0的整数'));
}else{
callback();
}
}, trigger: "blur"
}
]
}
(2).后端校验(JSR303)
前端实现了表单的校验,但是当我们绕过前端提交表单(如利用POSTMAN提交)的时候,数据没有实现校验,所以需要在后端也添加校验。
- 给bean添加校验注解
- 在控制类传来的数据上添加@Valid开启校验功能
- 给校验的bean后紧跟一个BindingResult,就可以获取到校验的结果
@NotBlank:主要用于校验字符串是否为空串或null,(注:只能用于String类型);
@NotNull:校验某字段对象不能为null;
@NotEmpty:主要用于校验集合数组等数据类型,不能为null,而且长度必须大于0;
@Pattern:主要校验入参是否符合正则式要求。
(3).后端校验—统一异常处理
注释掉我们之前的获取异常的代码,将异常抛出让异常处理类能接收到
系统错误码
错误码定义为5位数字 前两位表示业务场景,后三位表示错误码 定义为枚举形式,错误码+错误信息
如10001 10:通用 001:参数格式校验 11:商品 12:订单
当出现字段校验异常、其他异常时方便给前端返回指定微服务模块的code、msg
可以在comman模块封装一个枚举,在全局异常处理那里使用该枚举返回特定特征的code
package com.henu.soft.merist.common.exception;
public enum BizCodeEnume {
UNKNOW_EXCEPTION(10000,"系统未知异常!"),
VAILD_EXCEPTION(10001,"参数格式校验失败!");
private int code;
private String msg;
BizCodeEnume(int code,String msg){
this.code = code;
this.msg = msg;
}
public int getCode(){
return code;
}
public String getMsg(){
return msg;
}
}
package com.henu.soft.merist.gulimall.product.exception;
import com.henu.soft.merist.common.exception.BizCodeEnume;
import com.henu.soft.merist.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.henu.soft.merist.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.henu.soft.merist.gulimall.product.controller")//包含了@ResponseBody注解
public class GulimallExceptionControllerAdvice {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleVaildException(MethodArgumentNotValidException e){
log.error("数据校验异常{},异常类型{}",e.getMessage(),e.getClass());
BindingResult bindingResult = e.getBindingResult();
Map<String,String> map = new HashMap<>();
bindingResult.getFieldErrors().forEach((fieldError)->{
map.put(fieldError.getField(),fieldError.getDefaultMessage());
});
return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
}
@ExceptionHandler(value = Throwable.class)
public R handleThrowableException(Throwable e){
return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
}
}
(4).JSR303分组校验
同一个字段,在新增和修改的时候 校验规则 可能会不同,就需要用到分组校验
默认没有指定分组的校验注解,在分组校验的情况下不生效
(5).JSR303自定义校验注解
创建@ListValue校验注解
自定义注解要满足三个要求
- message:校验信息
- groups:分组校验
- Payload:自定义负载信息
创建一个配置文件
写一个自定义的校验器
package com.henu.soft.merist.common.valid;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;
public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {
private Set<Integer> set = new HashSet<>();
//初始化方法
//获取到所有范围内的值
@Override
public void initialize(ListValue constraintAnnotation) {
int[] vals = constraintAnnotation.vals();
for (int val : vals) {
set.add(val);
}
}
/**
* 判断是否校验成功
* @param value
* @param context
* @return
*/
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
}
}
注解绑定校验器