使用zTree进行数据动态显示

由于公司项目的须要。现学了一下zTree的使用。

以下是我项目的结构图:


baseDao类

package com.wiseweb.zTree;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BaseDao {
	static Connection conn ;
	PreparedStatement pstm ;
	ResultSet rs ;
	
	public static Connection getConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver") ;
			try {
				conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/crud", "root", "root") ;
				System.out.println("------------打开连接---------------");
			} catch (SQLException e) {
				System.out.println("------------连接失败---------------");
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			System.out.println("-----------------驱动载入失败---------------");
			e.printStackTrace();
		}
		return conn ;
	}
	public static void closeConnection(ResultSet rs,Statement st,Connection conn){
		try {
			if(rs != null){
				rs.close() ;
			}
			if(st != null){
				st.close() ;
			}
			if(conn != null){
				conn.close() ;
			}
			System.out.println("----------------关闭连接----------------");
		} catch (SQLException e) {
			System.out.println("----------------关闭连接失败----------------");
			e.printStackTrace();
		}
	}
}

实体Competence类

package com.wiseweb.zTree;

public class Competence {
	private int id ;
	private int pId ;
	private int isParent ;
	private String name ;
	private int open ;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getpId() {
		return pId;
	}
	public void setpId(int pId) {
		this.pId = pId;
	}
	public int getIsParent() {
		return isParent;
	}
	public void setIsParent(int isParent) {
		this.isParent = isParent;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getOpen() {
		return open;
	}
	public void setOpen(int open) {
		this.open = open;
	}
	
}

Test类
package com.wiseweb.zTree;

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

public class Test extends BaseDao{
	public List<Competence> getAllAuthorize(){
		List<Competence> authorizes = new ArrayList<Competence>() ;
		Connection conn = getConnection() ;
		try {
			pstm = conn.prepareStatement("select * from competence") ;
			rs = pstm.executeQuery() ;
			while(rs.next()){
				Competence authorize = new Competence() ;
				authorize.setId(rs.getInt("id")) ;
				authorize.setName(rs.getString("name")) ;
				authorize.setIsParent(rs.getInt("isParent")) ;
				authorize.setOpen(rs.getInt("open")) ;
				authorize.setpId(rs.getInt("pId")) ;
				authorizes.add(authorize) ;
			}
		} catch (SQLException e) {
			System.out.println("-----------查询competence失败-------------");
			e.printStackTrace();
		}finally{
			closeConnection(rs,pstm,conn) ;
		}
		return authorizes ;
	}
	public String getJsonData(){
		List<Competence> list = getAllAuthorize() ;
		StringBuffer json = new StringBuffer("[") ;
		String data = "" ;
		int length = list.size() ;
		for(int i=0;i<length;i++){
			json.append("{id:" + list.get(i).getId() + ",") ;
			json.append("pId:" + list.get(i).getpId() + ",") ;
			json.append("name:\"" + list.get(i).getName() + "\",") ;
			if(list.get(i).getIsParent() != 0){
				json.append("isParent:" + list.get(i).getIsParent() + ",") ;
			}
			if(list.get(i).getOpen() != 0){
				json.append("open:" + list.get(i).getOpen() + ",") ;
			}
			data = json.substring(0,json.lastIndexOf(",")) + "}," ;
			json = new StringBuffer(data) ;
		}
		data = json.substring(0,json.length()-1) + "]" ;
		System.out.println(data);
		return data ;
	}
	public static void main(String[] args) {
		new Test().getJsonData() ;
	}
}
asynload.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>asynload.html</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="css/demo.css" type="text/css">
    <link rel="stylesheet" href="css/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.5.js"></script>
	
	<script type="text/javascript">
		var setting = {
			async:{
				enable:true,
				url:"loadData.jsp",
				autoParam:["id"],
			},
			data:{
				simpleData:{
					enable:true,
					idKey:"id",
					pIdKey:"pId",
					rootPId:0
				}
			},
			callback:{
				onClick:function(event,treeId,treeNode,clickFlag){
					if(!treeNode.isParent){
						alert("treeId自己主动编号:" + treeNode.tId + ",节点id是:" + treeNode.id + ",节点文本是:" + treeNode.name) ;
					}
				},
				onAsyncError:zTreeOnAsyncError,
				onAsyncSuccess:function(event,treeId,treeNode,msg){

				}
			}
		};
		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 zTreeOnAsyncError(event,treeId,treeNode,XMLHttpRequest,textStatus,errorThrown){
			alert("载入错误:" + XMLHttpRequest) ;
		}
		$(document).ready(function(){
			$.fn.zTree.init($("#treeDemo"),setting) ;
		}) ;
	</script>
  </head>
  
  <body>
    <div>
    	<ul id="treeDemo" class="zTree"></ul>
    </div>
  </body>
</html>

index.jsp主程序

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>zTree</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">
	<link rel="stylesheet" href="${ctx }/css/demo.css" type="text/css">
    <link rel="stylesheet" href="${ctx }/css/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="${ctx }/js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="${ctx }/js/jquery.ztree.core-3.5.js"></script>
	
	<script type="text/javascript">
		var setting = {
			async:{
				enable:true,
				url:"loadData.jsp",
				autoParam:["id"],
			},
			data:{
				simpleData:{
					enable:true,
					idKey:"id",
					pIdKey:"pId",
					rootPId:0
				}
			},
			callback:{
				onClick:function(event,treeId,treeNode,clickFlag){
					if(!treeNode.isParent){
						alert("treeId自己主动编号:" + treeNode.tId + ",节点id是:" + treeNode.id + ",节点文本是:" + treeNode.name) ;
					}
				},
				onAsyncError:zTreeOnAsyncError,
				onAsyncSuccess:function(event,treeId,treeNode,msg){

				}
			}
		};
		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 zTreeOnAsyncError(event,treeId,treeNode,XMLHttpRequest,textStatus,errorThrown){
			alert("载入错误:" + XMLHttpRequest) ;
		}
		$(document).ready(function(){
			$.fn.zTree.init($("#treeDemo"),setting) ;
		}) ;
	</script>
  </head>
  
  <body>
     <div>
    	<ul id="treeDemo" class="zTree"></ul>
    </div>
  </body>
</html>

loadData.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.wiseweb.zTree.*" %>
<% 
	String id = request.getParameter("id") ;
	System.out.println("得到的节点id: " + id) ;
	Test demo = new Test() ;
	String json = demo.getJsonData() ;
	out.print(json) ;
%>

zTree.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>zTree.html</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="css/demo.css" type="text/css">
    <link rel="stylesheet" href="css/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.5.js"></script>
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
	
	<script type="text/javascript">
		function setFontCss(treeId,treeNode){
			return treeNode.level==0?{color:"red"}:{};
		}
		var setting = {
			data:{
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "pId",
					rootPId:0,
				}
			},
			view:{
				showLine: false,//是否显示连接线
				//showIcon: false,//是否显示节点图标
				//showTitle: false,//是否显示节点的title提示信息
				fontCss: setFontCss,//改变字体颜色和样式
			}
		};
		var zNodes = [
		              {id:1, pId:0, name:"父节点1-展开", open:true, iconOpen:"WEB-INF/image/1_open.png", iconClose:"WEB-INF/image/1_close.png"},
		              {id:11, pId:1, name:"父节点11-折叠", icon:"WEB-INF/image/2.png"},
		              {id:111, pId:11, name:"叶子节点111",url:"http://www.baidu.com"},//超链接
		              {id:112, pId:11, name:"叶子节点112"},
		              {id:113, pId:11, name:"叶子节点113"},
		              {id:114, pId:11, name:"叶子节点114"},
		              { id:12, pId:1, name:"父节点12 - 折叠"},
			  			{ id:121, pId:12, name:"叶子节点121"},
			  			{ id:122, pId:12, name:"叶子节点122"},
			  			{ id:123, pId:12, name:"叶子节点123"},
			  			{ id:124, pId:12, name:"叶子节点124"},
			  			{ id:13, pId:1, name:"父节点13 - 没有子节点", isParent:true},
			  			{ id:2, pId:0, name:"父节点2 - 折叠"},
			  			{ id:21, pId:2, name:"父节点21 - 展开", open:true},
			  			{ id:211, pId:21, name:"叶子节点211"},
			  			{ id:212, pId:21, name:"叶子节点212"},
			  			{ id:213, pId:21, name:"叶子节点213"},
			  			{ id:214, pId:21, name:"叶子节点214"},
			  			{ id:22, pId:2, name:"父节点22 - 折叠"},
			  			{ id:221, pId:22, name:"叶子节点221"},
			  			{ id:222, pId:22, name:"叶子节点222"},
			  			{ id:223, pId:22, name:"叶子节点223"},
			  			{ id:224, pId:22, name:"叶子节点224"},
			  			{ id:23, pId:2, name:"父节点23 - 折叠"},
			  			{ id:231, pId:23, name:"叶子节点231"},
			  			{ id:232, pId:23, name:"叶子节点232"},
			  			{ id:233, pId:23, name:"叶子节点233"},
			  			{ id:234, pId:23, name:"叶子节点234"},
			  			{ id:3, pId:0, name:"父节点3 - 没有子节点", isParent:true}
		];
		$(document).ready(function(){
			$.fn.zTree.init($("#treeDemo"),setting,zNodes) ;
		}) ;
	</script>
  </head>
  
  <body>
    <h1>最简单的树--简单的json数据</h1>
    <ul id="treeDemo" class="ztree"></ul>
  </body>
</html>


数据库图片:


浏览器输入http://localhost:8080/testZtree进行显示

结果为:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值