用java代码实现构造目录树-LMLPHP

怎么用java代码实现上面这样的目录树?

首先创建数据表

用java代码实现构造目录树-LMLPHP

每条数据记录自己的id以及父节点的id

然后进入java代码部分:

public String directory(String author)
{
StringBuffer treeHtml = new StringBuffer();
// 得到所有的目录词(包含全部字段)
List<Tutorial> words = bdExpandService.getAllWords(author);
for (int i = 0; i < words.size(); i++)
{
Tutorial wordMap = words.get(i);
// System.out.println(wordMap);
if (wordMap.getPid() == 0)
{
treeHtml.append("<dl>");
// 得到根目录的id,根据这个id找到这个的所有子目录
appendTree(words, wordMap, treeHtml);
treeHtml.append("</dl>");
}
}
words.clear();
return treeHtml.toString();
} /**
*
* 构造目录树 <功能详细描述>
*
* @param tutorials
* @param tutorial
* @param treeHtml
* @see [类、类#方法、类#成员]
*/
private void appendTree(List<Tutorial> words, Tutorial wordMap, StringBuffer treeHtml)
{
int tid = wordMap.getTid();
// 得到根目录的id,根据这个id找到这个的所有子目录
Map<String, Object> map = childTreeHtml(words, tid);
String nodeHtml = map.get("treeHtml").toString();
boolean hasChild = Boolean.valueOf(map.get("hasChild").toString());
if (hasChild)
{
treeHtml.append("<dt class='node-close' onclick='showTree(").append(tid).append(")'");
treeHtml.append("id='tree_dt").append(tid).append("'>");
treeHtml.append(wordMap.getKeyWord()).append("</dt>");
treeHtml.append(nodeHtml);
} else
{
treeHtml.append("<dt>");
treeHtml.append(wordMap.getKeyWord()).append("</dt>");
}
} /**
*
* 得到子目录,构造目录树 <功能详细描述>
*
* @param tutorials
* @param tid
* @return
* @see [类、类#方法、类#成员]
*/
private Map<String, Object> childTreeHtml(List<Tutorial> words, int tid)
{
Map<String, Object> map = new HashMap<String, Object>();
StringBuffer treeHtml = new StringBuffer();
boolean hasChild = false;
for (int i = 0; i < words.size(); i++)
{
Tutorial wordMap = words.get(i);
int pid = wordMap.getPid();
if (pid == tid)
{
hasChild = true;
treeHtml.append("<dd name='tree_dd").append(pid).append("'");
treeHtml.append("style='display: none;'>").append("<dl>");
appendTree(words, wordMap, treeHtml);
treeHtml.append("</dl></dd>");
}
}
map.put("treeHtml", treeHtml);
map.put("hasChild", hasChild);
return map;
}
JavaScript方法:
function showTree(tid)
{
var dds = $("dd[name='tree_dd" + tid + "']");
var dtClass = $("#tree_dt" + tid).attr("class");
if(dtClass == "node-close"){
$("#tree_dt" + tid).attr("class", "node-open");
$("dd[name='tree_dd" + tid + "']").each(function(){
$(this).show();
});
}else{
$("#tree_dt" + tid).attr("class", "node-close");
$("dd[name='tree_dd" + tid + "']").each(function(){
$(this).hide();
});
}
}
directory()方法返回的字符串就是整个目录树,然后将这个字符串传到前台页面显示,加上css样式就可以了
05-11 21:52