1.需求场景
数据库后台返回树形结构菜单,实现菜单排序。
2.项目环境
spring spring mvc mybatis mysql
3.实现方法
对应的实体类
private int id;// '主键ID',
private String cname;// '菜单名称',
private int pid;// '父级ID',默认0
private String redirect;// '菜单地址',
private String creator;// '创建者',
private String updatedate;// '修改日期',
private String updator;// '修改者',
private String createdate;// '创建日期',
private double sortid;//菜单排序字段 默认0
private List children;//父菜单下的子菜单封装树形数据
public class TreeUtil {
private int count = 0;
private List nodes;
public TreeUtil(List nodes){
this.nodes = nodes;
}
public List buildTree(){
List list = new ArrayList();
for (AuthUser node : nodes) {
if (node.getPid() == 0) {
list.add(node);
}
}
list = getSortChildren(list);
for (AuthUser node : list) {
build(node);
}
return list;
}
/***
* 构建权限树
* @Title: build
* @Description: TODO
* @param node
*/
private void build(AuthUser node){
List children = getChildren(node);
if (!children.isEmpty()) {
node.setChildren(children);
if(count <3){
//children.get(0).setChecked("true");//设置默认选中
count ++;
}
for (AuthUser child : children) {
build(child);
}
}
}
/**
*
* @Title: getChildren
* @Description: TODO 获取子节点
* @param node
* @return
*/
private List getChildren(AuthUser node){
List children = new ArrayList();
Integer id = node.getId();
for (AuthUser child : nodes) {
if (id==child.getPid()) {
children.add(child);
}
}
return getSortChildren(children);
// return children;
}
/**
*
* @Title: getChildren
* @Description: TODO 获取排序子节点
* @param node
* @return
*/
private List getSortChildren(List children){
MyCompare my = new MyCompare();
Collections.sort(children,my) ;
return children;
}
}自定义比较器
public class MyCompare implements Comparator{
@Override
public int compare(AuthUser o1, AuthUser o2) {
if(o1.getSortid()
return -1;
}else{
return 1;
}
}
}
数据库返回
public void getauthinfo(Map param){
List authList =userRoleService.getUserAuthTree(param); //执行查询
TreeUtil tree = new TreeUtil(authList);
//返回按照sortid排好序的树形结构的菜单
List datalist = tree.buildTree();
}
} catch (Exception e) {
e.printStackTrace();
}
}