EasyUI Tree的簡單使用

此前寫過zTree插件的demo,沒有記錄下來,此次記錄一下EasyUI的Tree。javascript

實現效果:獲取數據庫表的數據,以樹結構的形式展現出來。css

樹結構數據分爲同步加載和異步加載,同步加載就是初始化加載時直接將整個樹結構數據所有加載出來,異步加載則是初始化加載時只加載樹的根節點,當點擊某個節點時才向系統請求數據,若該節點有子節點則加載(只加載)出該節點的子節點(子節點的子節點不加載)。html

項目、框架、數據庫:建立的是Maven項目,採用Spring+SpringMVC+Mybatis框架,數據庫SQL Server 2005前端

1.建立數據庫表java

表結構:node

表數據:jquery

2.經過mybatis逆向工程映射TreeTestTable(表名略醜)git

TreeTestTable表的實體類代碼:github

package com.lwl.EasyUIDemo.bean;

public class TreeTestTable {
    private Integer id;

    private Integer pid;

    private String value;
    
    set/get方法...
}

3.編寫TreeBean類(因爲實際使用中表結構不一樣,所以須要編寫一個類用於將獲取到的數據對象轉爲前端Tree可以讀取並加載的數據格式):web

package com.lwl.EasyUIDemo.pojo;

import java.util.ArrayList;
import java.util.List;

import com.lwl.EasyUIDemo.bean.TreeTestTable;

public class TreeBean {
    
    private int id;
    private int pid;
    private String state;
    private String text;
    private List<TreeBean> children;
    
    /**
     * TreeTestTable對象轉TreeBean對象
     * @param treeList
     * @return
     */
    public static List<TreeBean> toTreeBeans(List<TreeTestTable> treeList){
        List<TreeBean> treeBeans = new ArrayList<TreeBean>();
        for (TreeTestTable tree : treeList) {
            TreeBean treeBean = new TreeBean(tree.getId(), tree.getPid(), tree.getValue(), new ArrayList<TreeBean>());
            treeBeans.add(treeBean);
        }
        return treeBeans;
    }
    
    /**
     * 獲取TreeBean對象列表
     * @param treeBeans
     * @return
     */
    public static List<TreeBean> getTreeBeanList(List<TreeBean> treeBeans){
        // 建立TreeBean對象列表
        List<TreeBean> treeBeanList = new ArrayList<TreeBean>();
        // 遍歷獲取到的List<TreeBean>對象列表
        for (TreeBean treeBean1 : treeBeans) {
            List<TreeBean> treeBeanChildren = treeBean1.getChildren();
            // 再次遍歷List<TreeBean>對象列表
            for (TreeBean treeBean2 : treeBeans) {
                // 當pid等於id時,將pid所在的對象存入同一個
                if (treeBean1.getId()==treeBean2.getPid()) {
                    TreeBean treeBean = new TreeBean(treeBean2.getId(), treeBean2.getPid(), treeBean2.getText(), treeBean2.getChildren());
                    // 存入父節點列表對象
                    treeBeanChildren.add(treeBean);
                }
            }
            // 設置children屬性
            treeBean1.setChildren(treeBeanChildren);
            // 判斷是不是0節點
            if (treeBean1.getPid()==0) {
                treeBeanList.add(treeBean1);
            }
        }
        return treeBeanList;
    }
    
    
    public TreeBean(int id, int pid, String text, List<TreeBean> children) {
        super();
        this.id = id;
        this.pid = pid;
        this.text = text;
        this.children = children;
    }

   public TreeBean() {}

 set/get方法... }

 4.編寫Controller層代碼(動態樹和靜態樹是分開寫的,下面是把兩個的代碼全貼出來):

package com.lwl.EasyUIDemo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwl.EasyUIDemo.bean.TreeTestTable;
import com.lwl.EasyUIDemo.pojo.DatagridBean;
import com.lwl.EasyUIDemo.pojo.TreeBean;
import com.lwl.EasyUIDemo.service.TreeTestTableService;

@Controller
public class TestController {
    
    @Autowired
    private TreeTestTableService treeService;

    
    /**
     * 靜態樹同步加載
     * @return
     */
    @RequestMapping("/getTree")
    @ResponseBody
    public JSON getTree(){
        // 獲取全部值
        List<TreeTestTable> treeList = treeService.getTree();
        List<TreeBean> treeBeans = TreeBean.getTreeBeanList(TreeBean.toTreeBeans(treeList));
        return  (JSON) JSON.toJSON(treeBeans);
    }
    
    /**
     * 動態樹異步加載(點擊無子節點的節點時請求)
     * @param id
     * @return
     */
    @RequestMapping("/getTreeById")
    @ResponseBody
    public JSON getTreeByPid(@RequestParam("id") int id){
        // 將id做爲pid獲取匹配數據
        List<TreeTestTable> treeList = treeService.getTreeByPid(id);
        List<TreeBean> treeBeans = TreeBean.toTreeBeans(treeList);
        return (JSON) JSON.toJSON(treeBeans);
    }
}

5.對照controller層方法所引用的service方法來建立service接口:

package com.lwl.EasyUIDemo.service;

import java.util.List;

import com.lwl.EasyUIDemo.bean.TreeTestTable;

public interface TreeTestTableService {

    /**
     * 獲取表的所有數據
     * @return
     */
    List<TreeTestTable> getTree();
    
    /**
     * 獲取匹配pid的數據
     * @return
     */
    List<TreeTestTable> getTreeByPid(int id);
}

Service實現類:

package com.lwl.EasyUIDemo.serviceImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lwl.EasyUIDemo.bean.TreeTestTable;
import com.lwl.EasyUIDemo.bean.TreeTestTableExample;
import com.lwl.EasyUIDemo.dao.TreeTestTableMapper;
import com.lwl.EasyUIDemo.service.TreeTestTableService;
@Service
public class TreeTestTableServiceImpl implements TreeTestTableService {

    @Autowired
    private TreeTestTableMapper tableMapper;

    /**
     * 獲取表的所有數據
     */
    public List<TreeTestTable> getTree() {
        return tableMapper.selectByExample(null);
    }

    /**
     * 獲取匹配pid的內容
     */
    public List<TreeTestTable> getTreeByPid(int id) {
        TreeTestTableExample example = new TreeTestTableExample();
        example.createCriteria().andPidEqualTo(id);
        return tableMapper.selectByExample(example);
    }
}

 6.編寫jsp頁面(關於EasyUI的使用格式等請自行查看EasyUI API文檔):

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<% pageContext.setAttribute("path", request.getContextPath()); %>
<!DOCTYPE>
<html>
<head>
<title>EasyUI實例</title>
<!-- 載入easyui樣式及圖標樣式 -->
<link rel="stylesheet" type="text/css" href="${path }/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${path }/easyui/themes/icon.css">
<!-- 載入jquery支持文件(必須寫在其餘js文件前)、easyui支持文件、easyui中文支持文件 -->
<script type="text/javascript" src="${path }/easyui/jquery.min.js"></script>
<script type="text/javascript" src="${path }/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${path }/easyui/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>
靜態樹加載:<br>
<ul id="staticTree"></ul><br>
動態樹加載:<br>
<ul id="dynamicTree"></ul>

<script>
    // 靜態樹加載
    $("#staticTree").tree({
        url:'getTree',
        onClick : function(node) {
            // 展開/摺疊
            if (node.state === 'open') {
                $('#staticTree').tree('collapse', node.target);
            } else {
                $('#staticTree').tree('expand', node.target);
            }
        },
        onLoadSuccess:function(node, data){// 加載成功後摺疊全部節點
            $('#staticTree').tree('collapseAll');
        } 
    });
    
    // 動態樹加載
    $("#dynamicTree").tree({
        url : 'getTreeById?id=0',
        onClick : function(node) {
            // 若所選節點爲空則執行請求
            if ($('#dynamicTree').tree('isLeaf', node.target)) {
                $.ajax({
                    url : 'getTreeById?id=' + node.id,
                    type : 'POST',
                    success : function(data) {
                        $('#dynamicTree').tree('append', {
                            parent : node.target,
                            data : data
                        })
                    }
                })
            }
            // 展開/摺疊
            if (node.state === 'open') {
                $('#dynamicTree').tree('collapse', node.target);
            } else {
                $('#dynamicTree').tree('expand', node.target);
            }
        }
    })
</script>
</body>
</html>

 運行看一下效果:

靜態樹在頁面載入時加載了完整的樹結構,而動態樹則只加載了根節點,當點擊節點時才載入子節點:

在數據表中添加兩個子節點:

動態加載樹,加載且只加載該節點的子節點:

當點擊動態樹的一號時:

 以上僅僅是本人接觸EasyUI Tree編寫的簡單例子,有任何理解或作法上的錯誤,歡迎批評指正!

相關文章
相關標籤/搜索