SSM+Easyui 动态Tree简单实现

SSM+Easyui 动态Tree简单实现

一、表结构:

SSM+Easyui 动态Tree简单实现
表1为信息表。此表设计没有要求 只需留给对应树ID的字段就可以了(rid与表2的id对应)。

SSM+Easyui 动态Tree简单实现
表2为树表
字段为Easyui树结构规定好的
id :树的id
text :展示树节点文本
state :closed表示有子节点,open表示没有子节点
checked:树初始化时是否打开
attribute:树的pid

二、代码实现上从功能入口上开始介绍:
SSM+Easyui 动态Tree简单实现
在页面访问的时候通过页面加载函数请求查询树表信息并反馈展示,达到树初始化。

<ul id="tt" class="easyui-tree"></ul>  //Easyui提供的树样式

$(function(){
	        $('#tt').tree({           //Easyui提供的树初始化
	            url:"<%=request.getContextPath()%>/address/tree.do"	// tree里的请求路径url
	        }); 
	    })

后台代码业务处理层:

public List<TreeVO> treeList() {
		List<TreeVO> listto= new ArrayList<>(); //创建一个子节点集合  目的在查询父节点是发现有子节点就放入
		List<TreeVO> tempList=addmapper.treeList();//查询树表中所有信息
		for (int i = 0; i < tempList.size(); i++) {
			if(tempList.get(i).getAttributes()==0) { //寻找最大的父节点(PID)
				List<TreeVO> list = getChildrenUtil(tempList.get(i).getId(),tempList);//调用方法递归查询节点
				tempList.get(i).setChildren(list);//将查询当前父节点下的子节点放入Children集合中让Easyui遍历子节点
				listto.add(tempList.get(i));//节点数据放入集合中
			}
		}
		return listto;//反馈到前台
    }


    public  List<TreeVO>  getChildrenUtil(int id,List<TreeVO> trees){
    	List<TreeVO> tempList = new ArrayList<>();//创建一个子节点集合  目的在查询父节点是发现有子节点就放入
        for (int i = 0; i < trees.size(); i++) {//循环参数中的集合
        	if(trees.get(i).getAttributes()==id) {//判断父节点是否与参数中的子节点匹配
	            List<TreeVO> treeVOS = getChildrenUtil(trees.get(i).getId(),trees);//递归调用自己  目的在于继续查找子节点直到没有
	            if(treeVOS.size()<=0) {// 如果集合中没有了子节点
	            	trees.get(i).setState("open"); //修改state属性为OPEN表示没有子节点。Easyui会终止树
	            }
	            trees.get(i).setChildren(treeVOS);//将查询当前父节点下的子节点放入Children集合中让Easyui遍历子节点
	            tempList.add(trees.get(i));//如果仍有下节点数据就放入集合中
        	}
        }
    	return tempList;//返回这个集合方便在递归是再次使用剩下的子节点
    }

动态点击功能实现:

$('#tt').tree({
	    	onClick: function(node){
	    		alert("此次查询树ID为:"+node.id);
	    			var a=node.id;
	    			var chandi=node.text;
		    			$('#dg').datagrid({    
		    			    url:'<%=request.getContextPath()%>/address/selectById.do?pid='+a,    
		    			    columns:[[
		    			        {field:'spid',title:'编码',width:100},    
		    			        {field:'spname',title:'名称',width:100},
		    			        {field:'spprice',title:'价格',width:100},  
		    			        {field:'spdate',title:'时间',width:100},  
		    			        {field:'sptype',title:'产地',width:100},
		    			        {field:'sppath',title:'图片',width:100},  
		    			        {field:'rid',title:'对应树ID',width:100}      
		    			    ]]    
		    			})
	    			
	    		}
	    })
		

通过node(Easyui提供的)属性可以获取到树的id从而可以定位到数据具体的Rid,ID选择器选择数据表格用datagrid在路径中加入树id返回致后台查询相应的数据,反馈数据后columns遍历
SSM+Easyui 动态Tree简单实现