權(quán)限系統(tǒng),Web開發(fā)常見標(biāo)準(zhǔn)子系統(tǒng)之一。結(jié)合自己的一些思考和實踐,從本篇開始權(quán)限系統(tǒng)的設(shè)計與實現(xiàn)之路。
最近,重構(gòu)了項目的權(quán)限菜單構(gòu)造過程,向前端返回json格式的權(quán)限樹。
這一篇,只是大致介紹下這個問題,并給出4種方法的整體思路,后續(xù)再分別詳細(xì)介紹這4種方法,再往后介紹完整的權(quán)限系統(tǒng)的設(shè)計與實現(xiàn)。
權(quán)限表的結(jié)構(gòu):
acl、parent_acl, 最重要的就是這2個字段,有了這2個字段,就可以構(gòu)造一棵樹了。
前端需要的json格式:
"data":[{
"acl":1,
"children":[{
"acl":11,
"children":[{
"acl":111,
}]
}
方法1:
在數(shù)據(jù)庫再增加1個level字段,最頂層的level就是1,每增加一級level增加1。
先從數(shù)據(jù)庫按照level升序,獲得所有的權(quán)限節(jié)點。
List<Map<String, Object>> rootList = new ArrayList<Map<String, Object>>();
Map<String, Map<String, Object>> rootMap = new HashMap<String, Map<String, Object>>();
for (遍歷) {
創(chuàng)建節(jié)點,加入到根節(jié)點map中
if (頂級節(jié)點) {
加入到rootList中
} else {
獲得父結(jié)點,把自己放到父結(jié)點的children中
}
}
遍歷結(jié)束,rootList即為所求。List<Map<String, Object>> rootList = findRootList(privilegeList);
List<Map<String, Object>> notRootList = findNotRootList(privilegeList);
//先找出根節(jié)點,再為這些根節(jié)點構(gòu)造子結(jié)點
for (Map<String, Object> root : rootList) {
// 構(gòu)造子結(jié)點
buildChildList(root, notRootList);
finalRootList.add(root);
}
關(guān)鍵代碼buildChildList是個遞歸函數(shù)。
buildChildList(){
從所有的非根節(jié)點中,找到當(dāng)前節(jié)點的第1級子結(jié)點,加入到該節(jié)點的children中。
buildChildList();
}
好處是,不用維護(hù)level字段,增加和修改權(quán)限的時候,既不用維護(hù)level,也不用維護(hù)parent_acl。
湖北-武漢-循禮門
原文首發(fā):http://fansunion.cn/article/detail/566.html