前言
最近在做项目的时候,在处理到菜单权限递归获取数据的时候,还很想了一会,这里做一个笔记,给后面的人共勉。虽然很简单~
dto
@Data
@ToString
@ApiModel("权限dto")
public class AuthorityDto {
@ApiModelProperty(value = "id")
private Integer id;
@ApiModelProperty(value = "父级ID")
private Integer parentId;
@ApiModelProperty(value = "菜单url地址")
private String url;
@ApiModelProperty(value = "菜单name")
private String name;
@ApiModelProperty(value = "菜单名称")
private String title;
@ApiModelProperty(value = "是否隐藏:0 false;1 true")
private Integer hidden;
@ApiModelProperty(value = "element ui图标")
private String icon;
@ApiModelProperty(value = "顺序")
private Integer ord;
@ApiModelProperty(value = "是否可用:0可用,1不可用")
private String struts;
@ApiModelProperty(value = "子集菜单")
private List<AuthorityDto> children;
}
业务处理
@Service
public class HlAuthorityServiceImpl extends ServiceImpl<HlAuthorityMapper, HlAuthority> implements HlAuthorityService {
@Override
public List<AuthorityDto> getAuthorityList(int userId) {
// 这里先查传userID,后面,应该还有角色ID的
List<AuthorityDto> list = getBaseMapper().getAuthorityByUserId(userId);
List<AuthorityDto> menuData = handlingMenuData(list);
return menuData;
}
/**
* 处理菜单数据
* @param menuList
* @return
*/
private List<AuthorityDto> handlingMenuData(List<AuthorityDto> menuList) {
List<AuthorityDto> authorityDtoList = new ArrayList<>();
// 循环菜单数据:拿到一级菜单数据
for (AuthorityDto authorityDto : menuList) {
int parentId = authorityDto.getParentId();
// 父级菜单ID为0,说明是一级菜单
if (0 == parentId) {
authorityDtoList.add(authorityDto);
}
}
// 循环一级菜单,主要是要循环迭代到下面的子菜单
for (AuthorityDto authorityDto : authorityDtoList) {
Integer id = authorityDto.getId();
// 获取子集菜单数据
authorityDto.setChildren(getChild(id, menuList));
}
return authorityDtoList;
}
/**
* 获取子集菜单数据
*
* @param id 父级ID
* @param menuList 菜单的所有数据
* @return
*/
private List<AuthorityDto> getChild(int id, List<AuthorityDto> menuList) {
// 定义子菜单的集合
List<AuthorityDto> childList = new ArrayList<>();
// 循环全部的数据
for (AuthorityDto menu : menuList) {
// 遍历所有节点,将父菜单id与传过来的id比较
int parentId = menu.getParentId();
// 如果菜单的父级ID和传过来的ID相同,说明是改ID下的菜单,我们就把菜单给放到集合装起来
if (parentId == id) {
childList.add(menu);
}
}
// 精华:我们在一次循环子菜单,得到下面的子菜单
for (AuthorityDto menu : childList) {
// 得到子集菜单的ID
int childId = menu.getId();
// 递归的迭代
menu.setChildren(getChild(childId, menuList));
}
// 递归退出条件,一定要有,不然就是死循环,系统直接GG
if (childList.size() == 0) {
return null;
}
return childList;
}
}