我们通过一张表实现二级菜单的封装功能,数据库表中存在一张菜单表,t_menu表,字段有id,menu_name,menu_url,parent_id,由于个人问题(没有在里面加logo什么的,如果小伙伴们需要的话,你们可以自己加一下)
其中,parent_id关联id,相当于是系统设置为父级菜单,参数配置为子菜单,我们在处理Java代码的时候,可以直接实现封装的功能。以service中代码为例,具体思路如下:
1:首先查出来父级菜单,parent_id为0的菜单都是父级菜单,返回的是一个list集合
2:迭代集合,然后拿到每一个父级菜单,然后根据这个父级菜单的ID去查询parent_id等于父级菜单的ID,然后放到一个集合中就可以了
具体代码如下
List<Menu> menus = mapper.selectAll();for (Menu menu :menus){Map fatherMap = new HashMap();fatherMap.put("id",menu.getId());fatherMap.put("name",menu.getMenuName());List children = new ArrayList();List<Menu> menuList = mapper.selectMenuListByParentId(menu.getId());if (menuList != null && menuList.size() > 0){for (Menu mu : menuList){Map smMap = new HashMap();smMap.put("id",mu.getId());smMap.put("name",mu.getMenuName());children.add(smMap);}fatherMap.put("children",children);}else{fatherMap.put("children",null);}}
拿到数据之后,直接返回就可以了。前端在通过后台拿到的数据来展示二级菜单就可以了!
如果觉得《java 实现二级动态菜单功能》对你有帮助,请点赞、收藏,并留下你的观点哦!