BootStrap Jstree 树形菜单的增删改查的实现源码
1.首先需下载jstree的插件点击打开链接
2.在页面引入插件js文件css文件
<link rel="stylesheet" href="plugins/jstree/themes/classic/style.css" rel="external nofollow" > <script type="text/javascript" src="plugins/jstree/_lib/jquery.js"></script> <script type="text/javascript" src="plugins/jstree/_lib/jquery.cookie.js"></script> <script type="text/javascript" src="plugins/jstree/_lib/jquery.hotkeys.js"></script> <script type="text/javascript" src="plugins/jstree/jquery.jstree.js"></script>
3.初始化控件
1)html
<div id="demo2" class="demo" style="height:100px;"></div>
2)js 使用 demo2来初始化树形控件
<script type="text/javascript" class="source below"> $(function() { $("#demo2").jstree( { "json_data" : { "ajax" : { "url" : "http://localhost:8080/membermanager/departmenttreejson", "data" : function(n) { // the result is fed to the ajax request `data` option return { "operation" : "get_children", "id" : n.attr ? n .attr( "id") .replace( "node_", "") : 1 }; } } }, "plugins" : [ "themes", "json_data", "ui", "crrm", "contextmenu", "search" ], }) .bind("loaded.jstree", function(event, data) { }) .bind( "select_node.jstree", function(event, data) { if (data.rslt.obj .attr("id") != undefined) { } }) .bind( "remove.jstree", function(e, data) { data.rslt.obj.each(function() { $.ajax({ async : false, type : 'post', url : "http://localhost:8080/membermanager/createnodefordepartment", data : { "operation" : "remove_node", "id" : this.id.replace("node_", "") }, success : function(r) { if (!r.status) { data.inst.refresh(); } } }); }); }) .bind( "remove.jstree", function(e, data) { data.rslt.obj.each(function() { $.ajax({ async : false, type : 'post', url : "http://localhost:8080/membermanager/createnodefordepartment", data : { "operation" : "remove_node", "id" : this.id .replace( "node_", "") }, success : function( r) { if (!r.status) { data.inst.refresh(); } } }); }); }) .bind( "create.jstree", function(e, data) { $.post( "http://localhost:8080/membermanager/createnodefordepartment", { "operation" : "create_node", "id" : data.rslt.parent .attr( "id") .replace( "node_", ""), "position" : data.rslt.position, "title" : data.rslt.name, "type" : data.rslt.obj .attr("rel") }, function(r) { if (r.status) { $(data.rslt.obj).attr("id", "node_" + r.id); } else { data.inst.refresh(); $.jstree.rollback(data.rlbk); } }); }) .bind( "rename.jstree", function(e, data) { $.post( "http://localhost:8080/membermanager/createnodefordepartment", { "operation" : "rename_node", "id" : data.rslt.obj .attr( "id") .replace( "node_", ""), "title" : data.rslt.new_name }, function(r) { if (!r.status) { data.inst.refresh(); $.jstree.rollback(data.rlbk); } }); }) // 1) the loaded event fires as soon as data is parsed and inserted // 2) but if you are using the cookie plugin or the core `initially_open` option: .one("reopen.jstree", function(event, data) { }) // 3) but if you are using the cookie plugin or the ui `initially_select` option: .one("reselect.jstree", function(event, data) { }); }); </script>
</pre>4.代码解析<p></p><p><pre name="code" class="java"> import java.util.list; public class department { // 部门id private string departmentid; // 部门名称 private string name; // 父级部门id private string parentid; //同级之间的排序。排序id 小的排前面 private string orders; //子节点 private list<department> childnode; public list<department> getchildnode() { return childnode; } public void setchildnode(list<department> childnode) { this.childnode = childnode; } public string getdepartmentid() { return departmentid; } public void setdepartmentid(string departmentid) { this.departmentid = departmentid; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getparentid() { return parentid; } public void setparentid(string parentid) { this.parentid = parentid; } public string getorders() { return orders; } public void setorders(string orders) { this.orders = orders; } @override public string tostring(){ return "[departmentid:"+this.departmentid+ "departmentname:"+this.name+ "parentid:"+this.parentid+"orders:"+this.orders+"]"; } }
4.代码解析
插件初始化我这里使用了插件的两个参数json_data,以及plugins注意看代码结构
4.1上图两个部分即初始化部分重点解释下plugins这个参数是jstree整合插件的地方theme表示主题,json_data将上文定义的json_data也就
是ajax从后要获取json数据返回到前台页面。contextmenu,是鼠标右键在树形节点上会弹出增删改查的菜单。
4.2 json数据的格式
先看展示
这是一个可以无限极下分的菜单,我们可以根据上图的目录结构对照下面的json数据结构来看,这样会更清晰。
{"data":"软件及数据","attr":{"id":"e59365b9-7b2a-43a3-b10a-cfe03d5eb004"}, "children":[ {"data":"创新组","attr":{"id":"73919359-2a1b-4ee7-bcc2-56949e8560e8"}, "children":[ {"data":"大数据","attr":{"id":"a7ea6a0f-0b78-4064-803b-f2e0a95d914f"}, "children":[ {"data":"研发","attr":{"id":"fc20e438-e7b9-4cca-be6a-49965daab528"},"children":[]}]}]}, {"data":"项目管理","attr":{"id":"e1bdae71-6cfb-4e8c-ab29-a3eb03b9961d"},"children":[]} ] },
4.4组装json数据,我使用的是首先查找到所有的父节点即parentid=1的时候,然后递归将所有的子节点加到list<chiledren>对象里面,紧接着再通过循环递归组装无限极菜单json数据下面看数据库数据结构
import java.util.list; public class department { // 部门id private string departmentid; // 部门名称 private string name; // 父级部门id private string parentid; //同级之间的排序。排序id 小的排前面 private string orders; //子节点 private list<department> childnode; public list<department> getchildnode() { return childnode; } public void setchildnode(list<department> childnode) { this.childnode = childnode; } public string getdepartmentid() { return departmentid; } public void setdepartmentid(string departmentid) { this.departmentid = departmentid; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getparentid() { return parentid; } public void setparentid(string parentid) { this.parentid = parentid; } public string getorders() { return orders; } public void setorders(string orders) { this.orders = orders; } @override public string tostring(){ return "[departmentid:"+this.departmentid+ "departmentname:"+this.name+ "parentid:"+this.parentid+"orders:"+this.orders+"]"; } }
4.5 此处servlet为客户端提供jstree的json_data。就是在初始化控件时候有ajax调用这个servlet获取json数据并返回给json_data
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 cn.goldwind.www.service.departmentservice; import cn.goldwind.www.serviceimpl.departmentserviceimpl; public class departmenttreejson extends httpservlet { /** * */ private static final long serialversionuid = 1l; public departmenttreejson() { super(); } @override public void destroy() { super.destroy(); // just puts "destroy" string in log // put your code here } @override public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { request.setcharacterencoding("utf-8"); response.setcontenttype("text/html;charset=utf-8"); printwriter out = response.getwriter(); departmentservice deptservice=new departmentserviceimpl(); //此处调用创建树节点的方法 stringbuilder json=deptservice.createtreenode(); json.deletecharat(json.length()-1); system.out.println(json); out.print("["+json+"]"); out.flush(); out.close(); } @override public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } @override public void init() throws servletexception { // put your code here } }
4.6上面servlet我们看下createtreenode方法
这里是创建json的核心。
1)首先获取所有的(parent=1)根节点
@override public stringbuilder createtreenode() { //创建部门集合 list<department> departments = new arraylist<department>(); //放置所有的根节点部门实体 departments = querybyparentid("1"); if (departments != null) { return json(departments); } return null; } public stringbuilder json(list<department> departments) { for (int i = 0; i < departments.size(); i++) { json.append('{'); json.append("\"data\":\"").append(departments.get(i).getname()) .append("\","); json.append("\"attr\":{\"id\":\"").append(departments.get(i).getdepartmentid()).append("\"},"); list<department> deptchild = querybyparentid(departments.get(i) .getdepartmentid()); json.append("\"children\":"); json.append('['); if (deptchild != null) { json(deptchild); if("1".equals(departments.get(i).getparentid())){ json.deletecharat(json.length()-1); json.append(']'); json.append('}'); json.append(','); }if(!"1".equals(departments.get(i).getparentid())&&deptchild!=null){ json.deletecharat(json.length()-1); json.append(']'); json.append('}'); json.append(','); } } else{ json.append(']'); json.append('}'); json.append(','); } } return json; } @override public list<department> querybyparentid(string parentid) { basedaotemplate bd = new basedaotemplate(); list<department> departments = new arraylist<department>(); string sql = "select departmentid,name,parentid,orders from department where parentid=? "; list<object> params = new arraylist<object>(); params.add(parentid); departments = bd.findalldata(department.class, sql, params); if (departments.size() > 0) { return departments; } return null; }
4.7
1.如何创建节点通过右键点击树形菜单弹出增加移除等操作(需在plugins里面加入contextmenu 这个例子就有)
2.绑定jstree的操作,此处以增加节点为例不一一例举
原理;通过点击创建按钮(contextmenu)即选定树节点右键弹出按钮。调用上图的方法,上图方法post方法通过ajax请求后台数据把创建的树节点保存到数据库,
operation:操作的方式(创建,移除,修改。。);
id:当前节点的id 即你创建下一个节点的parentid。
title:创建的新节点的名称
有这些数据就可以字啊后台获取数据然后增加到数据库。
4.8 创建 servlet处理所有的操作(创建,移除,修改。。)
import java.io.ioexception; import java.io.printwriter; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import cn.goldwind.www.pojo.department; import cn.goldwind.www.service.departmentservice; import cn.goldwind.www.serviceimpl.departmentserviceimpl; public class createnodefordepartment extends httpservlet { private static final long serialversionuid = 1l; public createnodefordepartment() { super(); } @override public void destroy() { super.destroy(); // just puts "destroy" string in log // put your code here } @override public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { request.setcharacterencoding("utf-8"); response.setcontenttype("text/html;charset=utf-8"); printwriter out = response.getwriter(); departmentservice deptservice=new departmentserviceimpl(); if("rename_node".equals(request.getparameter("operation"))){ string id=request.getparameter("id"); string title=request.getparameter("title"); department dept=new department(); dept.setdepartmentid(id); deptservice.modifydepartment(dept, title); }else if("create_node".equals(request.getparameter("operation"))){ string id=request.getparameter("id"); string title=request.getparameter("title"); department dept=new department(); dept.setdepartmentid(uuid.randomuuid().tostring()); dept.setname(title); dept.setparentid(id); deptservice.insertdepartment(dept); }else if("remove_node".equals(request.getparameter("operation"))){ string id=request.getparameter("id"); department dept=new department(); dept.setdepartmentid(id); deptservice.deletedepartment(dept); } out.flush(); out.close(); } /** * the dopost method of the servlet. <br> * * this method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws servletexception * if an error occurred * @throws ioexception * if an error occurred */ @override public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } /** * initialization of the servlet. <br> * * @throws servletexception * if an error occurs */ @override public void init() throws servletexception { // put your code here } }
好了这就完成了,当然这里面的树也是可以自定义图标,自定义按钮等操作,具体可以自己去探究。
以上所述是小编给大家介绍的bootstrap jstree 树形菜单的增删改查的实现源码,希望对大家有所帮助
上一篇: spring boot整合jsp及设置启动页面的方法
下一篇: c# datatable用法总结