大型商城:商品服务API-三级分类
1.查出所有分类
1.在gulimall-product的CategoryController中添加如下方法
/**
* 查询出所有分类以及子分类,以属性结构组装起来
*/
@RequestMapping("/list/tree")
public R list(){
List<CategoryEntity> entities = categoryService.listWithTree();
return R.ok().put("data", entities);
}
2.后在CategoryServer中添加对应接口,在CategoryServerImpl中添加实现方法
@Override
public List<CategoryEntity> listWithTree() {
//1.查出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);
//2.组装成父子的树形结构
//2.1 找到所有的一级分类
List<CategoryEntity> leve1Mens = entities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).map(menu->{
menu.setChildren(getChildrens(menu,entities));
return menu;
}).sorted((menu1,menu2)->{
return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
}).collect(Collectors.toList());
return leve1Mens;
}
//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildrens(CategoryEntity root , List<CategoryEntity> all){
List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map(categoryEntity -> {
//1.找到子菜单
categoryEntity.setChildren(getChildrens(categoryEntity,all));
return categoryEntity;
}).sorted((menu1,menu2)->{
//2.菜单的排序
return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
}).collect(Collectors.toList());
访问:http://127.0.0.1:10001/product/category/list/tree
2.配置网关路由与路径重写
接着操作后台 localhost:8001 , 点击系统管理->菜单管理->新增 目录->商品系统->一级菜单
添加的这个菜单其实是添加到了guli-admin.sys_menu表里
继续新增: 菜单->分类维护->商品系统->product/category menu
点击 分类维护,地址栏变为:http://localhost:8001/#/product-category 可以注意到product-category我们的/被替换为了-
比如sys-role具体的视图在renren-fast-vue/views/modules/sys/role.vue 所以要自定义我们的product/category视图的话,就是创建mudules/product/category.vue
后台获取分类需要给8080发请求读取数据,但是数据是在10000端口上,如果找到了这个请求改端口那改起来很麻烦。
方法1是改vue项目里的全局配置,搭建个网关,让网关路由到10000
Ctrl+Shift+F全局搜索
在static/config/index.js里 window.SITE_CONFIG['baseUrl'] = 'http://localhost:88/api'; (88是gateway的端口)
接着重新登录http://localhost:8001/#/login,验证码是请求88的,所以不显示。
而验证码是来源于fast后台的 现在的验证码请求路径为,http://localhost:88/api/captcha.jpg?uuid=69c79f02-d15b-478a-8465-a07fd09001e6
原始的验证码请求路径:http://localhost:8001/renren-fast/captcha.jpg?uuid=69c79f02-d15b-478a-8465-a07fd09001e6
fast注册到服务注册中心,这样请求88网关转发到8080fast
renren-fast中加入依赖:spring-cloud-starter-alibaba-nacos-discovery(可以引入gulimall-common)
在fast中添加
spring:
application:
name: renren-fast
cloud:
nacos:
discovery:
server-addr: localhost:8848 # nacos
然后在fast启动类上加上注解@EnableDiscoveryClient,重启
在gateway中按格式加入
- id: admin_route
uri: lb://renren-fast # 路由给renren-fast,lb代表负载均衡
predicates: # 什么情况下路由给它
- Path=/api/** # 默认前端项目都带上api前缀,
filters:
- RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment} #此规则就是删除/api/,接上/renren-fast/以及后面的内容
进行登录,发现还是报错
从8001访问88,引发CORS跨域请求,浏览器会拒绝跨域请求
3.配置跨域
跨域
问题描述:已拦截跨源请求:同源策略禁止读取位于 http://localhost:88/api/sys/login 的远程资源。(原因:CORS 头缺少 ‘Access-Control-Allow-Origin’)。
问题分析:这是一种跨域问题。访问的域名和端口和原来的请求不同,请求就会被限制
跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对js施加的安全限制。(ajax可以)
同源策略:是指协议,域名,端囗都要相同,其中有一个不同都会产生跨域;
前面跨域的解决方案:
方法1:设置nginx包含admin和gateway
方法2:让服务器告诉预检请求能跨域
解决方法:在网关中定义“GulimallCorsConfiguration”类,该类用来做过滤,允许所有的请求跨域。
@Configuration // gateway
public class GulimallCorsConfiguration {
@Bean // 添加过滤器
public CorsWebFilter corsWebFilter(){
// 基于url跨域,选择reactive包下的
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
// 跨域配置信息
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许跨域的头
corsConfiguration.addAllowedHeader("*");
// 允许跨域的请求方式
corsConfiguration.addAllowedMethod("*");
// 允许跨域的请求来源
corsConfiguration.addAllowedOrigin("*");
// 是否允许携带cookie跨域
corsConfiguration.setAllowCredentials(true);
// 任意url都要进行跨域配置
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
再次访问:http://localhost:8001/#/login
http://localhost:8001/renren已拦截跨源请求:同源策略禁止读取位于 http://localhost:88/api/sys/login 的远程资源。(原因:不允许有多个 ‘Access-Control-Allow-Origin’ CORS 头)n-fast/captcha.jpg?uuid=69c79f02-d15b-478a-8465-a07fd09001e6
出现了多个请求,并且也存在多个跨源请求。
为了解决这个问题,需要修改renren-fast项目,注释掉“io.renren.config.CorsConfig”类。然后再次进行访问。
4.树形展示三级分类数据
在显示商品系统/分类信息的时候,出现了404异常,请求的http://localhost:88/api/product/category/list/tree不存在
这是因为网关上所做的路径映射不正确,映射后的路径为http://localhost:8001/renren-fast/product/category/list/tree(上面配置的那个规则)
但是只有通过http://localhost:10000/product/category/list/tree路径才能够正常访问,所以会报404异常。
解决方法就是定义一个product路由规则,进行路径重写:
在网关增加三级分类的路由
- id: product_route
uri: lb://gulimall-product
predicates:
- Path=/api/product/**
filters:
- RewritePath=/api/(?<segment>.*),/$\{segment}
精确的路由规则放置到模糊的路由规则的前面,也就是说这个规则要配置到上一个规则的前面
整个后台三级分类菜单前端代码
删除 新增下级 拖拽排序 批量拖拽 批量删除
<!-- -->
<template>
<div>
<el-switch
v-model="draggable"
active-text="开启拖拽排序"
inactive-text="关闭拖拽排序"
>
</el-switch>
<el-button @click="batchSave">批量保存</el-button>
<el-button type="danger" @click="batchDelete">批量删除</el-button>
<!--
draggable: 拖拽是否开启 TRUE FALSE
@node-drop="handleDrop" :拖拽成功完成时触发的事件
根据返回的 TRUE与FALSE 判断能不能完成拖拽
-->
<el-tree
:data="menus"
:props="defaultProps"
@node-click="handleNodeClick"
: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 type="text" size="mini" @click="() => edit(data)">
修改
</el-button>
<el-button
v-if="node.level <= 2"
type="text"
size="mini"
@click="() => append(data)"
>
添加下級
</el-button>
<el-button
v-if="node.childNodes.length == 0"
type="text"
size="mini"
@click="() => remove(node, data)"
>
刪除
</el-button>
</span>
</span>
</el-tree>
<el-dialog :title="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-item label="图标">
<el-input v-model="category.icon" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="计量单位">
<el-input v-model="category.roductUnit" 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>
// 这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
// 例如:import 《组件名称》 from '《组件路径》';
import { add } from "../../../mock/modules/job-schedule";
export default {
// import引入的组件需要注入到对象中才能使用
components: {},
data() {
return {
pCid: [],
draggable: false,
updateNodes: [],
maxLevel: 0,
title: "",
dialogType: "",
category: {
name: "",
parentCid: 0,
catLevel: 0,
showStatus: 1,
sort: 0,
productUnit: "",
icon: "",
catId: null,
},
dialogVisible: false,
menus: [],
expandedKey: [],
defaultProps: {
children: "children",
label: "name",
},
};
},
// 监听属性 类似于data概念
computed: {},
// 监控data中的数据变化
watch: {},
// 方法集合
methods: {
handleNodeClick(data) {
console.log(data);
},
submitData() {
if (this.dialogType == "edit") {
this.editCategory();
}
if (this.dialogType == "add") {
this.addCategory();
}
},
batchDelete() {
let catIds = [];
let checkedNodes = this.$refs.menuTree.getCheckedNodes();
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.$notify({
title: "成功",
message: "批量删除成功!",
type: "success",
});
//刷新出新的菜单
this.getMenus();
//设置需要展开的默认菜单
this.expandedKey = [node.parent.data.catId];
});
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除",
});
});
},
batchSave() {
this.$http({
url: this.$http.adornUrl("/product/category/update/sort"),
method: "post",
data: this.$http.adornData(this.updateNodes, false),
}).then(({ data }) => {
this.$notify({
title: "成功",
message: "菜单修改成功!",
type: "success",
});
//刷新
this.getMenus();
//设置默认打开的菜单
this.expandedKey = this.pCid;
this.updateNodes = [];
this.maxLevel = 0;
//this.pCid = 0 ;
});
},
/*
拖拽成功完成时触发的事件
共四个参数,依次为:被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置(before、after、inner)、event
*/
handleDrop(draggingNode, dropNode, dropType, ev) {
//1.当前节点最新的父节点id
let pCid = 0;
let siblings = null;
if (dropType == "before" || dropType == "after") {
pCid = dropNode.parent.data.catId;
siblings = dropNode.parent.childNodes;
} else {
pCid = dropNode.data.catId;
siblings = dropNode.childNodes;
}
//当前拖拽节点的最新顺序
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.updataChildNodeLevel(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 });
}
}
this.pCid.push(pCid);
//3.当前拖拽节点的最新层级
console.log("new");
console.log("new", this.updateNodes);
},
updataChildNodeLevel(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.updataChildNodeLevel(node.childNodes[i]);
}
}
},
allowDrop(draggingNode, dropNode, type) {
//:allow-drop 根据返回的 TRUE与FALSE 判断能不能完成拖拽
// 1.三级菜单,所以被拖拽的当前节点以及所在的父节点 总层数不大于3
// 1>.被拖拽的当前节点总层数
console.log("a:", draggingNode, dropNode, type);
//
this.countNodeLevel(draggingNode);
//当前正在拖动的节点+父节点所在的深度不大于3即可
let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
//
if (type == "inner") {
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.dialogType = "edit";
this.title = "修改";
this.dialogVisible = true;
this.$http({
url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
methods: "get",
}).then(({ data }) => {
console.log("ssss", 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;
});
},
editCategory() {
var { catId, name, icon, productUnit } = this.category;
this.$http({
url: this.$http.adornUrl("/product/category/update"),
method: "post",
data: this.$http.adornData({ catId, name, icon, productUnit }, false),
}).then(({ data }) => {
this.$notify({
title: "成功",
message: "菜单修改成功!",
type: "success",
});
//关闭对话框
this.dialogVisible = false;
//刷新
this.getMenus();
//设置默认打开的菜单
this.expandedKey = [this.category.parentCid];
});
},
getMenus() {
this.$http({
url: this.$http.adornUrl("/product/category/list/tree"),
methods: "get",
}).then(({ data }) => {
console.log(data.data);
this.menus = data.data;
});
},
append(data) {
(this.title = "新增下级"), (this.dialogVisible = true);
this.dialogType = "add";
this.category.parentCid = data.catId;
this.category.catLevel = data.catLevel + 1;
this.category.catId = null;
this.category.name = "";
this.category.icon = "";
this.category.productUnit = "";
this.category.sort = 0;
this.category.showStatus = 1;
},
// 提交三級分類
addCategory() {
this.$http({
url: this.$http.adornUrl("/product/category/save"),
method: "post",
data: this.$http.adornData(this.category, false),
}).then(({ data }) => {
this.$notify({
title: "成功",
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.$notify({
title: "成功",
message: "删除成功!",
type: "success",
});
//刷新出新的菜单
this.getMenus();
//设置需要展开的默认菜单
this.expandedKey = [node.parent.data.catId];
});
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除",
});
});
console.log("hhh", node);
},
},
// 生命周期 - 创建完成(可以访问当前this实例)
created() {
this.getMenus();
},
// 生命周期 - 挂载完成(可以访问DOM元素)
mounted() {},
beforeCreate() {}, // 生命周期 - 创建之前
beforeMount() {}, // 生命周期 - 挂载之前
beforeUpdate() {}, // 生命周期 - 更新之前
updated() {}, // 生命周期 - 更新之后
beforeDestroy() {}, // 生命周期 - 销毁之前
destroyed() {}, // 生命周期 - 销毁完成
activated() {}, // 如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style scoped>
</style>