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注意看代碼結構
4.1上圖兩個部分即初始化部分重點解釋下plugins這個參數是jstree整合插件的地方theme表示主題,json_data將上文定義的json_data也就
是Ajax從后要獲取json數據返回到前臺頁面。contextmenu,是鼠標右鍵在樹形節點上會彈出增刪改查的菜單。
4.2 json數據的格式
先看展示
這是一個可以無限極下分的菜單,我們可以根據上圖的目錄結構對照下面的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的操作,此處以增加節點為例不一一例舉
原理;通過點擊創建按鈕(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 樹形菜單的增刪改查的實現源碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/u010288264/article/details/50896479