服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - BootStrap Jstree 树形菜单的增删改查的实现源码

BootStrap Jstree 树形菜单的增删改查的实现源码

2020-08-14 16:01_PPB Java教程

这篇文章主要介绍了BootStrap Jstree 树形菜单的增删改查的实现源码,非常不错,具有参考借鉴价值,需要的朋友可以参考下

1.首先需下载jstree的插件点击打开链接

2.在页面引入插件js文件css文件

?
1
2
3
4
5
6
7
<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

?
1
<div id="demo2" class="demo" style="height:100px;"></div>

2)js 使用 demo2来初始化树形控件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<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>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
</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注意看代码结构

BootStrap Jstree 树形菜单的增删改查的实现源码

4.1上图两个部分即初始化部分重点解释下plugins这个参数是jstree整合插件的地方theme表示主题,json_data将上文定义的json_data也就

是Ajax从后要获取json数据返回到前台页面。contextmenu,是鼠标右键在树形节点上会弹出增删改查的菜单。

4.2 json数据的格式

先看展示

BootStrap Jstree 树形菜单的增删改查的实现源码

这是一个可以无限极下分的菜单,我们可以根据上图的目录结构对照下面的json数据结构来看,这样会更清晰。

?
1
2
3
4
5
6
7
8
9
10
{"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数据下面看数据库数据结构

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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)根节点

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@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的操作,此处以增加节点为例不一一例举

BootStrap Jstree 树形菜单的增删改查的实现源码

原理;通过点击创建按钮(contextMenu)即选定树节点右键弹出按钮。调用上图的方法,上图方法post方法通过ajax请求后台数据把创建的树节点保存到数据库,

operation:操作的方式(创建,移除,修改。。);

id:当前节点的id 即你创建下一个节点的parentID。

title:创建的新节点的名称

有这些数据就可以字啊后台获取数据然后增加到数据库。

4.8 创建 servlet处理所有的操作(创建,移除,修改。。)

  1. import java.io.IOException; 
  2. import java.io.PrintWriter; 
  3. import java.util.UUID; 
  4. import javax.servlet.ServletException; 
  5. import javax.servlet.http.HttpServlet; 
  6. import javax.servlet.http.HttpServletRequest; 
  7. import javax.servlet.http.HttpServletResponse; 
  8. import cn.goldwind.www.pojo.Department; 
  9. import cn.goldwind.www.service.DepartmentService; 
  10. import cn.goldwind.www.serviceimpl.DepartmentServiceImpl; 
  11. public class CreateNodeForDepartment extends HttpServlet { 
  12.  private static final long serialVersionUID = 1L; 
  13.  public CreateNodeForDepartment() { 
  14.   super(); 
  15.  } 
  16.  @Override 
  17.  public void destroy() { 
  18.   super.destroy(); // Just puts "destroy" string in log 
  19.   // Put your code here 
  20.  } 
  21.  @Override 
  22.  public void doGet(HttpServletRequest request, HttpServletResponse response) 
  23.    throws ServletException, IOException { 
  24.   request.setCharacterEncoding("utf-8"); 
  25.   response.setContentType("text/html;charset=UTF-8"); 
  26.   PrintWriter out = response.getWriter(); 
  27.   DepartmentService deptService=new DepartmentServiceImpl(); 
  28.   if("rename_node".equals(request.getParameter("operation"))){ 
  29.    String id=request.getParameter("id"); 
  30.    String title=request.getParameter("title"); 
  31.    Department dept=new Department(); 
  32.    dept.setDepartmentid(id); 
  33.    deptService.modifyDepartment(dept, title); 
  34.   }else if("create_node".equals(request.getParameter("operation"))){ 
  35.    String id=request.getParameter("id"); 
  36.    String title=request.getParameter("title"); 
  37.    Department dept=new Department(); 
  38.    dept.setDepartmentid(UUID.randomUUID().toString()); 
  39.    dept.setName(title); 
  40.    dept.setParentid(id); 
  41.    deptService.insertDepartment(dept); 
  42.   }else if("remove_node".equals(request.getParameter("operation"))){ 
  43.    String id=request.getParameter("id"); 
  44.    Department dept=new Department(); 
  45.    dept.setDepartmentid(id); 
  46.    deptService.deleteDepartment(dept); 
  47.   } 
  48.   out.flush(); 
  49.   out.close(); 
  50.  } 
  51.  /** 
  52.   * The doPost method of the servlet. <br> 
  53.   * 
  54.   * This method is called when a form has its tag value method equals to 
  55.   * post. 
  56.   * 
  57.   * @param request 
  58.   *   the request send by the client to the server 
  59.   * @param response 
  60.   *   the response send by the server to the client 
  61.   * @throws ServletException 
  62.   *    if an error occurred 
  63.   * @throws IOException 
  64.   *    if an error occurred 
  65.   */ 
  66.  @Override 
  67.  public void doPost(HttpServletRequest request, HttpServletResponse response)  
  68.    throws ServletException, IOException { 
  69.   doGet(request, response); 
  70.  } 
  71.  /** 
  72.   * Initialization of the servlet. <br> 
  73.   * 
  74.   * @throws ServletException 
  75.   *    if an error occurs 
  76.   */ 
  77.  @Override 
  78.  public void init() throws ServletException { 
  79.   // Put your code here 
  80.  } 

好了这就完成了,当然这里面的树也是可以自定义图标,自定义按钮等操作,具体可以自己去探究。

以上所述是小编给大家介绍的BootStrap Jstree 树形菜单的增删改查的实现源码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/u010288264/article/details/50896479

延伸 · 阅读

精彩推荐