DIV CSS 佈局教程網

EasyUI 異步樹實作:展開時才向後端要子節點
編輯:JavaScript綜合知識     

同步樹一次載入全部資料,分類一多就慢。異步樹(又稱延遲載入)改為「展開哪一支才查那一支」,首屏只傳第一層,其餘按需索取。以下示範完整的三層實作。

運作原理

前台使用 EasyUI 的 tree 元件並指定 url。首次載入時向後端傳入的 id 為 null;之後每次使用者展開節點,EasyUI 就會把該節點的 id 當參數帶過來。後端據此判斷「要回傳根層級還是某節點的小孩」。

$('#tt').tree({ url: 'book/tree.do', method: 'get' });

Control 層

/**
 * 異步樹端點:id 為 null 表示要第一層
 */
@RequestMapping(value = "/tree.do")
public void mytree(HttpServletResponse response, String id) {
    this.writeJson(response, bookService.getChildrenTree(id));
}

Service 層

@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);
    }
}

DAO 層

@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());
}

異步樹最關鍵的設計:state 的決定

異步樹不像同步樹能一次看到全部結構,因此必須靠一次額外的 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 字串的寫法在整個專案中都要一併排查。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved