`

jQuery之Ztree

阅读更多
参考资料
1 spring+struts2+hibernate+json+dtree实现的无限级联树
http://luanmad-java.iteye.com/blog/459960
特别说明:数据库使用了以上这篇文章的表及相关数据
环境:XP+Oracle10i+Myeclipse6.6+JDK1.6
Ztree版本:3.0
工程图片如下:

运行效果如下:

一 前台代码如下:(tree.jsp)
<%@ page language="java" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<HTML>
<HEAD>
   <base href="<%=basePath%>">
	<TITLE> ZTREE DEMO - Async</TITLE>
	<meta http-equiv="content-type" content="text/html; charset=GBK">
	<link rel="stylesheet" href="css/demo.css" type="text/css">
	<link rel="stylesheet" href="css/zTreeStyle/zTreeStyle.css" type="text/css">
	<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
	<script type="text/javascript" src="js/jquery.ztree.core-3.0.js"></script>	
	<SCRIPT LANGUAGE="JavaScript">
		<!--
		var setting = {
			async: {
				enable: true,
				url:"treeNode",
				autoParam:["id", "name=n","url"],
				expandSpeed:false,				
				dataFilter: filter
			},
			callback: {
			    onClick: onClick,
				beforeAsync: beforeAsync,
				onCollapse: onCollapse,
				onExpand: onExpand
			}
		};
		
		function getTime() {
			var now= new Date(),
			h=now.getHours(),
			m=now.getMinutes(),
			s=now.getSeconds(),
			ms=now.getMilliseconds();
			return (h+":"+m+":"+s+ " " +ms);
		}
		
		function onCollapse(event, treeId, treeNode) {
			//alert("onCollapse: " + treeId + "," + treeNode.name + "," + treeNode.id+ "," + treeNode.url);
		}		
		
		function onExpand(event, treeId, treeNode) {
			//alert("onExpand: " + treeId + "," + treeNode.name+ "," + treeNode.id+ "," + treeNode.url);
		}
		
		function onClick(event, treeId, treeNode, clickFlag) {
			//alert("onClick: " + treeId + "," + treeNode.name + "," + clickFlag+ "," + treeNode.id+ "," + treeNode.url);
		}		

		function filter(treeId, parentNode, childNodes) {
			if (!childNodes) return null;
			for (var i=0, l=childNodes.length; i<l; i++) {
				childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
			}
			return childNodes;
		}
		function beforeAsync(treeId, treeNode) {
			return treeNode ? treeNode.level < 5 : true;
		}

		$(document).ready(function(){
			$.fn.zTree.init($("#treeDemo"), setting);
		});
		//-->
	</SCRIPT>
</HEAD>

<BODY>
<div class="content_wrap" >
	<div class="zTreeDemoBackground left">
		<ul id="treeDemo" class="ztree"></ul>
	</div>	
</div>
</BODY>
</HTML>

二 后台代码如下:
1 TreeNodeServlet.java
package net.liuzd.tree.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.liuzd.util.StringUtils;
import net.liuzd.util.UtilCommon;

public class TreeNodeServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			 {
		String pId = request.getParameter("id");
		String pName =  StringUtils.chineseStrUTF8(request.getParameter("n"));	
		System.out.println("PID: " + pId + ",pName: " + pName);
		// 构造数据,可以从数据库中查询
		String str = null;		
		if (pId == null) {			
			pId = "0";	
		} 		
		str = UtilCommon.getChild(pId);		
		try {
			reponse(request, response, str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}
	
	public void reponse(HttpServletRequest request,
			HttpServletResponse response, Object msg) throws Exception {
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(msg.toString());
		out.flush();
		out.close();
	}
}

2 树菜单类(BaseTreeNode.java)
package net.liuzd.tree;

import java.io.Serializable;

import org.apache.commons.lang.builder.ToStringBuilder;

public class BaseTreeNode implements Serializable {

	
	private static final long serialVersionUID = 1L;
	/**定义树控件公共属性*/
	
	/**树控件ID*/
	protected String treeId;
	/**树控件的名称*/
	protected String treeName;
	/**树控件的父ID*/
	protected String parentId;	
	/**是否为父项,或者说是否有子项*/
	protected boolean isParent;
	/**控件标题*/
	protected String treeTitle;
	
	public String getTreeId() {
		return treeId;
	}
	public BaseTreeNode setTreeId(String treeId) {
		this.treeId = treeId;
		return this;
	}
	public String getTreeName() {
		return treeName;
	}
	public void setTreeName(String treeName) {
		this.treeName = treeName;
	}
	public String getParentId() {
		return parentId;
	}
	public void setParentId(String parentId) {
		this.parentId = parentId;
	}
	
	
	public boolean isParent() {
		return isParent;
	}
	public void setParent(boolean isParent) {
		this.isParent = isParent;
	}
	public String getTreeTitle() {
		return treeTitle;
	}
	public void setTreeTitle(String treeTitle) {
		this.treeTitle = treeTitle;
	}
	
	public BaseTreeNode() {
		
	}
	
	public BaseTreeNode(String treeId, String treeName, String parentId,boolean isParent) {		
		this.treeId = treeId;
		this.treeName = treeName;
		this.parentId = parentId;				
		this.isParent = isParent;
	}	
	
	
	public BaseTreeNode(String treeId, String treeName, String parentId,boolean isHasChild,String treeTitle) {
		this(treeId,treeName,parentId,isHasChild);	
		this.treeTitle = treeTitle;
		
	}	
	
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}

3 DAO(TreeDAO.java)
package net.liuzd.tree.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.liuzd.tree.BaseTreeNode;

public class TreeDAO implements ITree {

	public void add(BaseTreeNode tree) {

	}

	public void del(BaseTreeNode tree) {

	}

	public BaseTreeNode get(BaseTreeNode tree) {

		BaseTreeNode bean = null;

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			String treeId = tree.getTreeId();
			String sql = "select * from TREENODES where ID=?";
			conn = ConnectionUtils.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, treeId);
			rs = ps.executeQuery();
			while (rs.next()) {
				bean = new BaseTreeNode(rs.getString("ID"), rs
						.getString("NAME"), rs
						.getString("PID"), isExpand(new BaseTreeNode().setTreeId(treeId)));
			}
			return bean;
		} catch (SQLException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				if (null != rs) {
					rs.close();
					rs = null;
				}
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				throw new RuntimeException("关闭数据库连接出错..." + e.getMessage(), e);
			}
		}

	}

	public List<BaseTreeNode> getChildTree(BaseTreeNode tree) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<BaseTreeNode> children = new ArrayList<BaseTreeNode>();
		try {
			String treeId = tree.getTreeId();
			String sql = "select * from TREENODES where PID=?";
			conn = ConnectionUtils.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, treeId);
			rs = ps.executeQuery();
			while (rs.next()) {
				treeId = rs.getString("ID");
				children.add(new BaseTreeNode(treeId, rs
						.getString("NAME"), rs
						.getString("PID"), isExpand(new BaseTreeNode().setTreeId(treeId))));
			}
			return children;
		} catch (SQLException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				if (null != rs) {
					rs.close();
					rs = null;
				}
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				throw new RuntimeException("关闭数据库连接出错..." + e.getMessage(), e);
			}
		}
	}

	public void update(BaseTreeNode tree) {

	}

	public boolean isExpand(BaseTreeNode tree) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			String treeId = tree.getTreeId();
			String sql = "select count(1) counts from TREENODES where PID=?";
			conn = ConnectionUtils.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, treeId);
			rs = ps.executeQuery();
			int counts = 0;
			while (rs.next()) {
				counts = rs.getInt(1);
			}
			return counts > 0;
		} catch (SQLException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				if (null != rs) {
					rs.close();
					rs = null;
				}
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				throw new RuntimeException("关闭数据库连接出错..." + e.getMessage(), e);
			}
		}
	}
}

4 工具类(UtilCommon.java)
package net.liuzd.util;

import java.util.List;

import net.liuzd.tree.BaseTreeNode;
import net.liuzd.tree.dao.ITree;
import net.liuzd.tree.dao.TreeDAO;

public class UtilCommon {
	
	public static String getRoot(String treeId) {
		String s = "";
		ITree treeDao = new TreeDAO();
		BaseTreeNode node = treeDao.get(new BaseTreeNode().setTreeId(treeId));
		s = "[";
		s += "{\"id\":\"" + node.getTreeId() + "\",\"name\":\"" + node.getTreeName()
						+ "\",\"isParent\":" + node.isParent()+ "}";			
		s = s.substring(0, s.length() - 1);
		s += "]";			
		return s;
	}
	
	public static String getChild(String treeId) {		
		String s = "[";
		ITree treeDao = new TreeDAO();
		List<BaseTreeNode> children = treeDao.getChildTree(new BaseTreeNode().setTreeId(treeId));
		for (BaseTreeNode node : children) {
			s += "{\"id\":\"" + node.getTreeId() + "\",\"name\":\"" + node.getTreeName()
			+ "\",\"isParent\":" + node.isParent()+ "},";
		}
		s = s.substring(0, s.length() - 1);
		s += "]";		
		return s;
	}

	public static void main(String[] args) {
		System.out.println(getRoot("513400000000"));
	}
}

5 数据库文件(oracle)
A 创建表数据
create table TREENODES
(
  id            NUMBER not null,
  pid           NUMBER not null,
  name          VARCHAR2(200) not null,
  url           VARCHAR2(200) not null,
  title         VARCHAR2(200),
  target        VARCHAR2(20),
  icon          VARCHAR2(200),
  sort          NUMBER not null,
  fontstylename VARCHAR2(500),
  iconopen      VARCHAR2(80),
  open          CHAR(1)
)

B 插入数据
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(35,0,'aaa','/index.jsp','aaa',NULL,'images/ajax_dtree/folder.gif',10,'font-weight:bold;font-size:14px;color:#0066FF',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(36,0,'bbb','/index.jsp','bbb',NULL,'images/ajax_dtree/folder.gif',2,'font-weight:bold;font-size:14px;color:#009900',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(37,36,'ccc','#','ccc',NULL,'images/ajax_dtree/folder.gif',3,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(39,35,'ggg','/index.jsp','ggg',NULL,'images/ajax_dtree/folder.gif',4,'font-weight:bold;font-size:14px;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(40,35,'fff','/index.jsp','fff',NULL,'images/ajax_dtree/folder.gif',5,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(92,35,'切实可行','/index.jsp','切实可行',NULL,'images/ajax_dtree/folder.gif',6,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(93,92,'优胜劣汰','/index.jsp','优胜劣汰',NULL,'images/ajax_dtree/folder.gif',7,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(94,92,'举国欢腾','/index.jsp','举国欢腾',NULL,'images/ajax_dtree/folder.gif',8,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(95,35,'基本原理','/index.jsp','基本原理',NULL,'images/ajax_dtree/folder.gif',9,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(96,0,'基本功','/index.jsp','基本功',NULL,'images/ajax_dtree/folder.gif',1,'font-weight:bold;font-size:14px;color:#9933CC',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(97,96,'艺术大师','/index.jsp','艺术大师',NULL,'images/ajax_dtree/folder.gif',11,'font-weight:bold;;;color:#999900',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(98,0,'lanmad!','/index.jsp','lanmad!',NULL,'images/ajax_dtree/folder.gif',12,'font-weight:bold;font-size:20px;color:#FF0000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(99,98,'架构与J2EE技术','/index.jsp','架构与J2EE技术',NULL,'images/ajax_dtree/folder.gif',19,'font-weight:bold;;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(100,98,'WEB开发(脚本神功与动态技术)','/index.jsp','WEB开发(脚本神功与动态技术)',NULL,'images/ajax_dtree/folder.gif',18,'font-weight:bold;;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(101,98,'Linux技术','#','Linux技术',NULL,'images/ajax_dtree/folder.gif',13,'font-weight:bold;;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(102,96,'中国','/index.jsp','中国',NULL,'images/ajax_dtree/folder.gif',16,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(103,96,'草木灰','#','草木灰',NULL,'images/ajax_dtree/folder.gif',17,';;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(104,98,'官方经典实例','#','官方经典实例',NULL,'images/ajax_dtree/folder.gif',14,'font-weight:bold;;;color:#000000',NULL,NULL);
insert  into treenodes(id,pid,name,url,title,target,icon,sort,fontStyleName,iconOpen,open) 
values(105,98,'数据库开发','#','数据库开发',NULL,'images/ajax_dtree/folder.gif',15,'font-weight:bold;;;color:#000000',NULL,NULL);

参见工程如下
  • 大小: 35.2 KB
  • 大小: 20.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics