同步樹一次載入全部資料,分類一多就慢。異步樹(又稱延遲載入)改為「展開哪一支才查那一支」,首屏只傳第一層,其餘按需索取。以下示範完整的三層實作。
前台使用 EasyUI 的 tree 元件並指定 url。首次載入時向後端傳入的 id 為 null;之後每次使用者展開節點,EasyUI 就會把該節點的 id 當參數帶過來。後端據此判斷「要回傳根層級還是某節點的小孩」。
$('#tt').tree({ url: 'book/tree.do', method: 'get' });
/**
* 異步樹端點:id 為 null 表示要第一層
*/
@RequestMapping(value = "/tree.do")
public void mytree(HttpServletResponse response, String id) {
this.writeJson(response, bookService.getChildrenTree(id));
}
@Transactional
@Override
public List<Tree> getChildrenTree(String pid) {
try {
List<Tree> result = new ArrayList<Tree>();
// 取得子節點清單
List<TBookType> childrenList = this.getChildrenType(pid);
if (childrenList != null && childrenList.size() > 0) {
for (TBookType child : childrenList) {
// 關鍵:查詢這個節點底下還有沒有孫節點
long count = bookDao.getChildrenCount(String.valueOf(child.getId()));
Tree node = new Tree();
node.setId(String.valueOf(child.getId()));
node.setPid(String.valueOf(child.getPid()));
node.setText(child.getName());
node.setChildren(null); // 異步樹不預先給子節點
// 有小孩 → 顯示收合與展開箭頭;沒有 → 就是葉節點
node.setState(count > 0 ? "closed" : "open");
result.add(node);
}
}
return result;
} catch (Exception e) {
throw new BusinessException("獲取圖書類型數據出現錯誤!", e);
}
}
@Override
public List<TBookType> getChildrenType(String pid) {
// pid 為 null 時取頂層,否則取該節點的直接子節點
StringBuilder sqlstr = new StringBuilder();
if (StringUtils.isBlank(pid))
sqlstr.append("select * from booktype bt where bt.pid=0");
else
sqlstr.append("select * from booktype bt where bt.pid=" + pid);
return this.search2(TBookType.class, sqlstr.toString());
}
@Override
public long getChildrenCount(String pid) {
// 用來判斷是否要顯示展開箭頭
StringBuilder sqlstr = new StringBuilder();
if (StringUtils.isBlank(pid))
sqlstr.append("select count(*) from booktype tb where tb.pid='0'");
else
sqlstr.append("select count(*) from booktype tb where tb.pid='" + pid + "'");
return this.count(sqlstr.toString());
}
異步樹不像同步樹能一次看到全部結構,因此必須靠一次額外的 count 查詢來判斷每個節點是否還有子節點:
state: "closed",EasyUI 會顯示展開箭頭,使用者點下去才會再發一次請求。state: "open",節點被視為葉節點,沒有箭頭。若懶得查 count,一律回傳 "closed" 也能跑,但使用者會點到一堆展開後空空的節點,體驗很差。這個 count 是異步樹必要成本。
| 同步樹 | 異步樹 | |
|---|---|---|
| 首次載入 | 整棵樹一次傳完 | 只傳第一層 |
| 展開時 | 純前端,零請求 | 每次展開一次請求 |
| 適合規模 | 數十至數百節點 | 上千節點以上 |
| 前端搜尋 | 可直接在本地過濾 | 需另外向後端查詢 |
上面的 SQL 是直接的字串拼接:"... where bt.pid=" + pid。由於 pid 來自前端傳遞,這等於把 SQL 注入的大門敞開——攻擊者只要傳入 1 or 1=1 就能撈出全部資料,更進一步甚至可能執行其他語句。
正確做法務必使用參數化查詢:
// 以 PreparedStatement / ORM 的參數綁定
String sql = "select * from booktype bt where bt.pid = ?";
jdbcTemplate.query(sql, new Object[]{ pid }, rowMapper);
這不是「有空再改」的小事,而是上線前必須處理的項目。同理,把 id 直接插入 SQL 字串的寫法在整個專案中都要一併排查。