@RequestMapping("/tree")
public void tree(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.writeJson(response, bookService.getTree());
}
@Override
public List getTree() {
try {
List trees = new ArrayList<>();
List roots = this.search(0); // 根節點 pid=0
if (roots != null && !roots.isEmpty()) {
for (TBookType tb : roots) {
Tree rootNode = this.getNode(tb);
rootNode.setState("open"); // 根節點預設展開
trees.add(rootNode);
}
}
return trees;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// 遞歸構建節點
private Tree getNode(TBookType node) {
if (node == null) return null;
try {
Tree treeNode = new Tree();
treeNode.setId(String.valueOf(node.getId()));
treeNode.setText(node.getName());
treeNode.setPid(String.valueOf(node.getPid()));
List children = this.search(node.getId());
if (children != null && !children.isEmpty()) {
treeNode.setState("closed"); // 有子節點預設折疊
for (TBookType child : children) {
Tree childNode = this.getNode(child); // 遞歸
if (childNode != null) {
treeNode.getChildren().add(childNode);
}
}
}
return treeNode;
} catch (Exception e) {
throw new BusinessException("獲取數據出錯!", e);
}
}
// 查詢子節點列表
public List search(Long pid) {
// SELECT * FROM booktype WHERE pid = ?
}
$('#tree').tree({
url: '/tree', // 指向後端 Controller
// 同步樹無需額外配置,直接渲染完整 JSON
});
{
"id": "1",
"text": "根節點",
"pid": "0",
"state": "open", // 或 "closed"
"children": [
{ "id": "2", "text": "子節點", "pid": "1", "state": "open", "children": [] }
]
}
| 維度 | 同步樹 | 異步樹 |
|---|---|---|
| 首屏載入 | 較慢(全量資料) | 極快(僅根節點) |
| 展開響應 | 極快(本地渲染) | 需 AJAX 請求 |
| 資料量適用 | < 1000 節點 | 無上限 |
| 後端複雜度 | 遞歸組裝 | 分頁查詢 + 狀態判斷 |
| 前端記憶體 | 較高 | 較低 |
同步樹實現簡單,核心在後端遞歸組裝完整樹結構 JSON。適合中小型靜態分類樹(如選單、地區選擇)。大數據量或動態頻繁變更場景請改用異步樹。