如何将数据库中存的树转化为树形列表(以easyui的tree为例)
程序员文章站
2024-03-15 18:23:36
...
代码实现
Tree 类
public class Tree {
private String id;
private String text;
private String url;
private String state;
private String iconCls;
private String privilegeID;//权限ID
private String isLeaf;//'叶子节点0否1是',
private String checked ;//是否选中
private String parentID ;//父节点ID
private String nodeType ;//节点类型
private String nodeTypeValue ;//节点类型
private List<Tree> children;
/**
*
* @Description (系统菜单--》菜单管理 获取功能列表)
* @param response
* @param request
*/
@RequestMapping(value = "/menu/getTree.do")
public void getTree(HttpServletResponse response,HttpServletRequest request,String parentID){
String tree = treeService.getTree(parentID);
ResponseUtils.renderJson(response, tree);
}
treeService
public String getTree(String parentID) {
//获取根节点
List<Tree> Trees = treeDao.getByPid(parentID);
List<Tree> bulidTree =this.bulidTree(Trees);
JSONArray JSONArrays = JSONArray.fromObject(bulidTree);
return StringUtil.StringToJson(JSONArrays.toString());
}
//获取root节点的子节点
public List<Tree> bulidTree(List<Tree> root){
for (int i=0;i<root.size();i++) {
//如果该节点是父节点,将该节点当做root节点,递归bulidTree
try {
List<Tree> sonTrees = treeDao.getByPid(root.get(i).getId());
bulidTree(sonTrees);
root.get(i).setChildren(sonTrees);
} catch (Exception e) {
// 没有获取到数据
e.printStackTrace();
continue;
}
}
return root;
}
treeDao.getByPid(String parentID)
<select id="getByPid" resultMap="tree" >
select
MenuID,
Title,
PageUrl,
IconName
from Menu
where
PrivilegeID in(
select PrivilegeID from UserPrivilegeTemp
where UserID=#{uid,jdbcType=INTEGER}
) and
ParentID=#{parentID,jdbcType=VARCHAR}
and IsActive='1'
ORDER BY Sequence desc
</select>