三级分类
1、基本概念
2、三级分类的商品表结构
3、代码编写(主要是后端的)
3.1 商品数据查询-封装成树形结构
- com.atguigu.gulimall.product.controller.CategoryController代码编写
@RequestMapping("/list/tree")
public R list() {
List entities = categoryService.listWithTree();
return R.ok().put("data", entities);
}
- com.atguigu.gulimall.product.service.impl.CategoryServiceImpl
@Override
public List listWithTree() {
//1、查出所有分类,baseMapper就是CategoryDao
List entities = baseMapper.selectList(null);
//2、组装成父子结构
//2.1找到所有1级分类
List level1Menus = entities.stream().filter(categoryEntity ->
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 level1Menus;
}
//递归查找所有菜单的子菜单
private List getChildrens(CategoryEntity root, List all) {
List children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid().equals(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());
return children;
}
3.2三级分类前端页面控件选择
- 在菜单管理中新建分类维护页面,在这个页面中进行商品三级分类管理
- 在view文件下创建product文件夹,并创建category相关的vue文件
3.3跨域问题解决
- 前面已经决定用gateway(网关)解决跨域问题,网关端口为88,前端统一设置baseUrl,发送到网关中,由网关统一配送请求。
- 由于前端在88后面+/api,导致路由结果出错,登录页面无法获得由renren-fast返回的验证码,因此在网关中增加一个路由判断。同时将renren-fast服务注测进nacos。网关中的路由顺序需要注意,模糊的路由放在后面,越后面优先级越低
- 登录页面地址为localhost:8001,后续请求发送到88端口会产生跨域问题(协议,域名,端口任意一个不同就会产生跨域),此处直接在网关出进行配置。同时注释掉人人开源服务模块中配置的跨域
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1、配置跨域
//跨域请求暴露的字段
corsConfiguration.addAllowedHeader("*");
//支持哪些方法跨域
corsConfiguration.addAllowedMethod("*");
//支持哪些来源请求
corsConfiguration.addAllowedOrigin("*");
//设置true表示跨域请求可以包含cookie
corsConfiguration.setAllowCredentials(true);
//注册跨域的配置,**表示任意路径都要进行跨域配置
source.registerCorsConfiguration("/**",corsConfiguration );
return new CorsWebFilter(source);
}
}
3.4树形展示三级分类
- 在nacos中创建product的命名空间,用命名空间做项目配置隔离(目前暂时没用到)
- application.yml配置