zTree树形结构框架连接数据库实现增删改

声明:此博文是根据网上一位大神的文章写的,和这位大神的著作大同小意,非常感谢这位大神。

1、zTree介绍:

zTree 是一个依靠 jQuery 实现的多功能 “树插件”。优异的性能、灵活的配置、多种功能的组合是 zTree 最大优点。
专门适合项目开发,尤其是 树状菜单、树状数据的Web显示、权限管理等等。
zTree 是开源免费的软件(MIT 许可证)。在开源的作用下,zTree 越来越完善,目前已经拥有了不少粉丝,并且今后还会推出更多的 zTree 扩展功能库,让 zTree 更加强大。

2、zTree特点:

zTree v3.0 将核心代码按照功能进行了分割,不需要的代码可以不用加载
采用了 延迟加载 技术,上万节点轻松加载,即使在 IE6 下也能基本做到秒杀
兼容 IE、FireFox、Chrome、Opera、Safari 等浏览器
支持 JSON 数据
支持静态 和 Ajax 异步加载节点数据
支持任意更换皮肤 / 自定义图标(依靠css)
支持极其灵活的 checkbox 或 radio 选择功能
提供多种事件响应回调
灵活的编辑(增/删/改/查)功能,可随意拖拽节点,还可以多节点拖拽哟
在一个页面内可同时生成多个 Tree 实例
简单的参数配置实现 灵活多变的功能

3、zTree优化:

zTree 的作者利用业余时间不断改进 zTree 功能,并且还能及时与用户沟通,及时回复各种疑问,便于新用户快速掌握。
目前越来越多的用户都使用 zTree 替换了系统中原有的 树插件,这其中包括最近刚发布最新版本的 QUI 框架。
大家也可以从官网http://www.ztree.me/v3/main.php#_zTreeInfo看一些列子、下包!本处以提供(JQuery zTree v3.3.zip);

4、zTree整体解析:

首先把JQuery zTree v3.3.zip解压放到web目录下(可以根据业务需求自定义),然后看一下代码应用的整体结构:

以自己的demo为例:

zTree树形结构框架连接数据库实现增删改_第1张图片

4.1:引入zTree相关的js、css文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="zTree/css/demo.css" type="text/css">
<link rel="stylesheet" href="zTree/css/zTreeStyle/zTreeStyle.css"
	type="text/css">
<script type="text/javascript" src="zTree/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="zTree/js/jquery.ztree.excheck.js"></script>
<script type="text/javascript" src="zTree/js/jquery.ztree.exedit.js"></script>

4.2:zTree异步加载的一些配置,业务需求不同篇日志也不同,看图分析:


5、自己写的一个小demo,连接数据库实现了增删改

数据库创建:

JsonDataServlet.java

package com.xbmu.demo;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.xbmu.bean.Car;
import com.xbmu.utils.DBCPUtil;
@WebServlet(urlPatterns="/jsondata")
public class JsonDataServlet extends HttpServlet {
	QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = req.getParameter("method");
		if("deletePp".equals(method)){
			deletePp(req,resp);
		}else if("addPp".equals(method)){
			addPp(req,resp);
		}else if("updatePp".equals(method)){
			updatePp(req,resp);
		}
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String data = getData();
		resp.getWriter().write(data);
	}
	//更新节点
	private void updatePp(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		req.setCharacterEncoding("utf-8");
		String id = req.getParameter("id");
		id = URLDecoder.decode(id,"utf-8");
		String name = req.getParameter("name");
		name = URLDecoder.decode(name,"utf-8");
		try {
			String sql = "update car set name=? where id=?";
			int update = qr.update(sql, name,id);
			if(update==1){
				System.out.println("修改成功");
			}else{
				System.out.println("修改失败");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//增加节点
	private void addPp(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String pId = req.getParameter("pId");
		pId = URLDecoder.decode(pId,"utf-8");
		String name = req.getParameter("name");
		name = URLDecoder.decode(name,"utf-8");
		
		try {
			String sql = "insert into car(pId,name) values(?,?)";
			int update = qr.update(sql, pId,name);
			if(update==1){
				System.out.println("添加成功");
			}else{
				System.out.println("添加失败");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//删除节点
	private void deletePp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
	
		String id = req.getParameter("id");
		id = URLDecoder.decode(id,"utf-8");
		String sql = "delete from car where id=?";
		try {
			int update = qr.update(sql, id);
			if(update==1){
				System.out.println("删除成功");
			}else{
				System.out.println("删除失败");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	public  String getData(){
		
		String sql = "select * from car";
		JSONArray array = new JSONArray();
		try {
			List<Car> carList = qr.query(sql, new BeanListHandler<Car>(Car.class));
			for (Car car : carList) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id",car.getId());
				jsonObject.put("name",car.getName());
				jsonObject.put("pId",car.getpId());
				array.put(jsonObject);
			}
			System.out.println(array.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return array.toString();
	}
	
}
test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="zTree/css/demo.css" type="text/css">
<link rel="stylesheet" href="zTree/css/zTreeStyle/zTreeStyle.css"
	type="text/css">
<script type="text/javascript" src="zTree/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="zTree/js/jquery.ztree.excheck.js"></script>
<script type="text/javascript" src="zTree/js/jquery.ztree.exedit.js"></script>
<script type="text/javascript">
	var setting = {
		async : {
			enable : true,//开启异步加载处理
			url : encodeURI(encodeURI("/peTreeDemo2/jsondata")),
			autoParam : [ "id" ],
			dataFilter : filter,
			contentType : "application/json",
			type : "get"
		},
		view : {
			expandSpeed : "",
			addHoverDom : addHoverDom,
			removeHoverDom : removeHoverDom,
			selectedMulti : false
		},
		edit : {
			enable : true
		},
		data : {
			simpleData : {
				enable : true
			}
		},
		callback : {
			beforeRemove : beforeRemove,
			beforeRename : beforeRename,
		}
	};
	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 beforeRemove(treeId, treeNode) {
		if (confirm("确认删除节点--" + treeNode.name + "--吗?")) {
			var param = "id=" + treeNode.id;
			$.post(encodeURI(encodeURI("/peTreeDemo2/jsondata?method=deletePp&"
					+ param)));
		} else {
			return false;
		}
	}
	function beforeRename(treeId, treeNode, newName) {
		if (newName.length == 0) {
			alert("节点名称不能为空.");
			return false;
		}
		var param = "id=" + treeNode.id + "&name=" + newName;
		$.post(encodeURI(encodeURI("/peTreeDemo2/jsondata?method=updatePp&"
				+ param)));
		return true;
	}

	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0)
			return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
				+ "' title='add node' onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_" + treeNode.tId);
		if (btn)
			btn.bind("click", function() {
				var Ppname = prompt("请输入新节点名称");
				if (Ppname == null) {
					return;
				} else if (Ppname == "") {
					alert("节点名称不能为空");
				} else {
					var param ="&pId="+ treeNode.id + "&name=" + Ppname;
					var zTree = $.fn.zTree.getZTreeObj("treeDemo");
					$.post(
							encodeURI(encodeURI("/peTreeDemo2/jsondata?method=addPp&"
									+ param)), function(data) {
								if ($.trim(data) != null) {
									var treenode = $.trim(data);
									zTree.addNodes(treeNode, {
										pId : treeNode.id,
										name : Ppname
									}, true);
								}
							})
				}

			});
	};
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_" + treeNode.tId).unbind().remove();
	};
	$(document).ready(function() {
		$.fn.zTree.init($("#treeDemo"), setting);

	});
</script>
<style type="text/css">
.ztree li span.button.add {
	margin-left: 2px;
	margin-right: -1px;
	background-position: -144px 0;
	vertical-align: top;
	*vertical-align: middle
}
</style>
</head>
<body>
	<div class="content_wrap">
		<div class="zTreeDemoBackground left">
			<ul id="treeDemo" class="ztree"></ul>
		</div>
	</div>
</body>
</html>
运行效果:

zTree树形结构框架连接数据库实现增删改_第2张图片
自己的写的一个小demo和网上一位大神做的笔记的下载地址:http://download.csdn.net/detail/btt2013/9479377


你可能感兴趣的:(ztree,树形框架)