java_easyui体系之Tree的加载

java_easyui体系之Tree的加载


一:简介


        实现三种Tree的初始化工作、并且重点叙述使用ajax动态加载树。

        1、  使用class属性初始化树

        2、  使用javascript初始化树

        3、  使用ajax动态加载树

        4、  使用ajax初始化树、使树所有节点展开

 

二:效果图

 



三:实现步骤


        1、使用class初始化树


                a)        定义树状结构的html文档、指定使用class=”easyui-tree”属性、可在data-options中添加自己想要的属性或方法、事件


	<ul id="tt" class="easyui-tree" data-options="lines:true">
		<li><span>Folder</span>
			<ul>
				<li><span>Sub Folder 1</span>
					<ul>
						<li><span><a href="#">File 11</a> </span></li>
						<li><span>File 12</span></li>
						<li><span>File 13</span></li>
					</ul>
				</li>
				<li><span>File 2</span></li>
				<li><span>File 3</span></li>
			</ul>
		</li>
		<li><span>File21</span></li>
	</ul>


        2、使用javascript初始化树


                a)        定义一个用于放置Tree的ul标签


	<ul id="tt2"></ul>

                b)        使用javascript初始化


	$(function() {
		//使用javascript初始化
		$('#tt2').tree({
			data : [ {
				"id" : 1,
				"text" : "Folder1",
				"iconCls" : "icon-save",
				"children" : [ {
					"text" : "File1",
					"checked" : true
				}, {
					"text" : "Books",
					"state" : "open",
					"attributes" : {
						"url" : "/demo/book/abc",
						"price" : 100
					},
					"children" : [ {
						"text" : "PhotoShop",
						"checked" : true
					}, {
						"id" : 8,
						"text" : "Sub Bookds",
						"state" : "closed"
					} ]
				} ]
			}, {
				"text" : "Languages",
				"state" : "closed",
				"children" : [ {
					"text" : "Java"
				}, {
					"text" : "C#"
				} ]
			} ]
		});
	});

     

        3、使用ajax动态加载树


                a)        前期准备工作

                                     i.             创建数据库、用于存放Tree信息、这里使用的hibernate自动创建、这里补充一个大意的地方、当我写好TreeDTO和其配置文件的时候、启动程序却怎么样也不给我创建表、崩溃的最后找到原因、原来在applicationContext.xml中没有将hibernate映射文件加载到mappingResource中:图




                                    ii.             数据库中初始手动添加的数据:图




                                   iii.             用于生成保存Tree信息的Java Bean:TreeDTO代码


package com.chy.ssh.business.bean;

import java.io.Serializable;

@SuppressWarnings("serial")
public class TreeDTO implements Serializable{
	private String id;
	private String pid;
	private String text;
	private String url;
	private int seq;
	
	
	public TreeDTO() {
		super();
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPid() {
		return pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public int getSeq() {
		return seq;
	}
	public void setSeq(int seq) {
		this.seq = seq;
	}
}


                                   iv.             用于构建Json字符串返回到前台显示的EasyUITree代码


package com.chy.ssh.business.bean.modal;

import java.io.Serializable;
import java.util.Map;

@SuppressWarnings("serial")
public class EasyUITree implements Serializable{
	private String id;
	private String text;
	private Boolean checked = false;
	private Map<String, Object> attributes;
	private String state = "open";
	
	//省略getXXX() setXXX()方法	
}


                b)        主要步骤:

                                     i.             前台:仅仅一个URL请求、他会自动的将id传到后台、不用我们从新获取再用别的代码改变参数去请求后台——代码:


	$(function() {
		//异步动态加载树
		$('#tt3').tree({
			url : 'treeAction_treeLoad.action',
			lines : true,
			checkbox : true,
		});

	});

                                    

                                    ii.             后台:根据传来的id查询记录、处理字符串(开始传入的id为null、这里查询是要判断一下)

                                    TreeAction中代码:


	public void treeLoad(){
		//从数据库中查询的保存tree的集合、比如id、父类id、text等等、可自己扩展
		List<TreeDTO> list = treeService.getTreesByParentId(id);
		//用于前台显示的tree的属性、比如id、state、text、checked等等
		List<EasyUITree> eList = new ArrayList<EasyUITree>();
		if(list.size() != 0){
			for(TreeDTO t : list){
				EasyUITree e = new EasyUITree();
				e.setId(t.getId());
				e.setText(t.getText());
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("url", t.getUrl());
				e.setAttributes(attributes);
				int count = treeService.countChildrens(t.getId());
				if(count > 0){
					//注意state这个属性、当他为open时、说明这个节点是个文件夹、会以文件夹的形式显示、
					//当他是closed的时候、说明这个节点是一个具体的文件节点、不会以文件夹的形式显示。
					e.setState("closed");
				}
				eList.add(e);
			}
		}
		id = null;
		//将含有用于显示tree的信息的集合、转换成json格式、传到前台。
		WriteJson.pwObj(eList);
	}

                                    底层DAO中代码:


	public List<TreeDTO> getTreesByParentId(String id) {
		StringBuffer hql = new StringBuffer();
		if(id == null || "".equals(id)){
			hql.append("from TreeDTO t where t.pid is null ");
		}else{
			hql.append("from TreeDTO t where t.pid = '"+id+"' ");
		}	
		List<TreeDTO> list = new ArrayList<TreeDTO>();
		try {
			list = this.getHibernateTemplate().find(hql.toString());
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return list;
	}


                                   iii.             将查询、处理后的结果集使用json工具处理成json格式字符串、传到前台用于显示

                                   WriteJson.pwObj(eList)的实现:


package com.chy.ssh.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

public class WriteJson {
	public static String getJson(Object o) {
		StringWriter sw = new StringWriter();
		try {
			ObjectMapper om = new ObjectMapper();
			JsonGenerator jg = new JsonFactory().createJsonGenerator(sw);
			om.writeValue(jg, o);
			jg.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sw.toString();
	}

	public static void pwObj(Object obj){
		try {
			PrintWriter pw = ServletActionContext.getResponse().getWriter();
			pw.print(getJson(obj));
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

        4、使用ajax一次性加载树

                  有前面的东西这里就很简单了:只要在初始化树时为其添加一个onLoadSuccess事件就好、代码:

//异步动态加载树
		$('#tt3').tree({
			url : 'treeAction_treeLoad.action',
			lines : true,
			checkbox : true,
			onLoadSuccess : function(node, data) {

				console.info(node);
				console.info(data);
				var t = $(this);
				if (data) {
					$(data).each(function(index, d) {
						if (this.state == 'closed') {
							t.tree('expandAll');
						}
					});
				}
			}
		});

四:源码补充


        1、tree.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'tree.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<jsp:include page="../inc.jsp"></jsp:include>
<script type="text/javascript">
	$(function() {
		//使用javascript初始化
		$('#tt2').tree({
			data : [ {
				"id" : 1,
				"text" : "Folder1",
				"iconCls" : "icon-save",
				"children" : [ {
					"text" : "File1",
					"checked" : true
				}, {
					"text" : "Books",
					"state" : "open",
					"attributes" : {
						"url" : "/demo/book/abc",
						"price" : 100
					},
					"children" : [ {
						"text" : "PhotoShop",
						"checked" : true
					}, {
						"id" : 8,
						"text" : "Sub Bookds",
						"state" : "closed"
					} ]
				} ]
			}, {
				"text" : "Languages",
				"state" : "closed",
				"children" : [ {
					"text" : "Java"
				}, {
					"text" : "C#"
				} ]
			} ]
		});

		//异步动态加载树
		$('#tt3').tree({
			url : 'treeAction_treeLoad.action',
			lines : true,
			checkbox : true,
			onLoadSuccess : function(node, data) {

				console.info(node);
				console.info(data);
				var t = $(this);
				if (data) {
					$(data).each(function(index, d) {
						if (this.state == 'closed') {
							t.tree('expandAll');
						}
					});
				}
			}
		});

	});
</script>
</head>

<body>
	<h2>initial tree by class :</h2>
	<ul id="tt" class="easyui-tree" data-options="lines:true">
		<li><span>Folder</span>
			<ul>
				<li><span>Sub Folder 1</span>
					<ul>
						<li><span><a href="#">File 11</a> </span></li>
						<li><span>File 12</span></li>
						<li><span>File 13</span></li>
					</ul>
				</li>
				<li><span>File 2</span></li>
				<li><span>File 3</span></li>
			</ul>
		</li>
		<li><span>File21</span></li>
	</ul>
	<br />
	<h2>initial tree by javascript:</h2>
	<ul id="tt2"></ul>
	<br />
	<h2>Dynamic load tree :</h2>
	<br />
	<ul id="tt3"></ul>
	<br />
</body>
</html>

       

        2、TreeAction:


package com.chy.ssh.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.chy.ssh.business.bean.TreeDTO;
import com.chy.ssh.business.bean.modal.EasyUITree;
import com.chy.ssh.business.service.TreeService;
import com.chy.ssh.utils.WriteJson;
import com.opensymphony.xwork2.ActionSupport;

public class TreeAction extends ActionSupport {
	
	private static final long serialVersionUID = 1L;
	private TreeService treeService;
	private String id;
	
	public void treeLoad(){
		//从数据库中查询的保存tree的集合、比如id、父类id、text等等、可自己扩展
		List<TreeDTO> list = treeService.getTreesByParentId(id);
		//用于前台显示的tree的属性、比如id、state、text、checked等等
		List<EasyUITree> eList = new ArrayList<EasyUITree>();
		if(list.size() != 0){
			for(TreeDTO t : list){
				EasyUITree e = new EasyUITree();
				e.setId(t.getId());
				e.setText(t.getText());
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("url", t.getUrl());
				e.setAttributes(attributes);
				int count = treeService.countChildrens(t.getId());
				if(count > 0){
					//注意state这个属性、当他为open时、说明这个节点是个文件夹、会以文件夹的形式显示、
					//当他是closed的时候、说明这个节点是一个具体的文件节点、不会以文件夹的形式显示。
					e.setState("closed");
				}
				eList.add(e);
			}
		}
		id = null;
		//将含有用于显示tree的信息的集合、转换成json格式、传到前台。
		WriteJson.pwObj(eList);
	}
	
	public TreeService getTreeService() {
		return treeService;
	}
	public void setTreeService(TreeService treeService) {
		this.treeService = treeService;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
}

        3、底层TreeDAOImpl  中间serveice省略:


package com.chy.ssh.business.dao;

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

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.chy.ssh.business.bean.TreeDTO;

public class TreeDAOImpl extends HibernateDaoSupport implements TreeDAO {

	
	
	public int countChildrens(String id) {
		return Integer.parseInt(String.valueOf(this.getHibernateTemplate().find("select count(*) from TreeDTO t where t.pid = '"+id+"'").get(0)));
	}

	@SuppressWarnings("unchecked")
	public List<TreeDTO> getTreesByParentId(String id) {
		StringBuffer hql = new StringBuffer();
		if(id == null || "".equals(id)){
			hql.append("from TreeDTO t where t.pid is null ");
		}else{
			hql.append("from TreeDTO t where t.pid = '"+id+"' ");
		}	
		List<TreeDTO> list = new ArrayList<TreeDTO>();
		try {
			list = this.getHibernateTemplate().find(hql.toString());
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return list;
	}
}


更多内容 : java_easyui体系之目录——00


  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值