利用easyUI的树来实现对角色权限的管理
easyUI 树的格式:
{
"id":1,
"text":"Foods",
"children":[{
"id":2,
"text":"Fruits",
"state":"closed",
"children":[{
"text":"apple",
"checked":true
},{
"text":"orange"
}]
},{
"id":3,
"text":"Vegetables",
"state":"open",
"children":[{
"text":"tomato",
"checked":true
},{
"text":"carrot",
"checked":true
},{
"text":"cabbage"
},{
"text":"potato",
"checked":true
},{
"text":"lettuce"
}]
}]
}]
java生成tree的数据结构,并转化成json传到前端:
//先获取系统所有权限
List<TRules> ruleList = tRulesService.selectAllRules();
//获取所有模块
List<TRules> moduleList = tRulesService.selectAllModules();
//根据角色获取当前用户所有权限
String roleRules = tRoleRulesService.selectAllRulesByRoleName(roleName);
//生成树的格式 text对应module,children 对应role
ArrayList<HashMap<String,Object>> userRoleList = new ArrayList<HashMap<String, Object>>();
//初始化模块
for(int i = 0; i < moduleList.size(); i++){
HashMap<String,Object> roleMap = new HashMap<String, Object>();
roleMap.put("id",i+1);
roleMap.put("text",moduleList.get(i).getModule());//生成模块的节点
roleMap.put("state","open");
roleMap.put("children",new ArrayList<HashMap<String,Object>>());//子树用于保存该模块下的权限
userRoleList.add(roleMap);
}
//初始化权限
for(int i =0; i < ruleList.size(); i++){
for(int j = 0; j < userRoleList.size(); j++){
HashMap<String,Object> roleMap = userRoleList.get(j);
//找到对应的模块
if(roleMap.get("text").equals(ruleList.get(i).getModule())){
HashMap<String,Object> childMap = new HashMap<String, Object>();
childMap.put("id",roleMap.get("id") + "" + (i+1));
childMap.put("text",ruleList.get(i).getRuleName());
//如果当前用户有这个权限,则勾选上
if(!Util.isBlank(roleRules) && roleRules.contains(ruleList.get(i).getRuleName()))
childMap.put("checked","true");
//放到children中
ArrayList<HashMap<String,Object>> list = (ArrayList)roleMap.get("children");
list.add(childMap);
break;
}
}
}
String listJson = JSON.toJSONString(userRoleList);