English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
1.Firstly, you need to download the jstree plugin and click on the link to open
2.Include plugin js file css file in the page
<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.initialize control
1)html
<div id="demo2" class="demo" style="height:100px;"/div>
2)js using demo2to initialize the tree control
<script type="text/javascript" class="source below"> $(function() { $("#demo2").jstree( { "json_data" : { "ajax" : { "url" : "http://MemberManager8080/,/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://MemberManager8080/,/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://MemberManager8080/,/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( localhost://MemberManager8080/,/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( localhost://MemberManager8080/,/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.Code parsing</p></.<p><pre name="code" class="java"> import java.util.List; public class Department { // Department ID private String departmentid; // Department name private String name; // Parent department ID private String parentid; //Sorting among the same level. The one with a smaller sorting ID is placed in front private String orders; //Child node 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.Code parsing
For plugin initialization, I used two parameters json_data and plugins, and pay attention to the code structure
4.1The two parts in the figure above, that is, the initialization part, focuses on explaining the plugins parameter, which is the place for integrating plugins in jstree. theme represents the theme, and json_data refers to the json_data defined above.
is to get JSON data from the backend and return it to the front-end page through Ajax. The contextmenu is a menu that pops up for add, delete, modify, and search operations when the right mouse button is clicked on a tree node.
4.2 format of JSON data
Let's take a look at the display
This is a menu that can be infinitely divided, and we can compare the directory structure in the figure above with the JSON data structure below to make it clearer.
{"data":"Software and Data","attr":{"id":"e}59365b9-7b2a-43a3-b10a-cfe03d5eb004"} },"children":[ {"data":"Innovation Group","attr":{"id":"}73919359-2a1b-4ee7-bcc2-56949e8560e8"} },"children":[ {"data":"Big Data","attr":{"id":"a7ea6a0f-0b78-4064-803b-f2e0a95d914f"}, },"children":[ {"data":"Research and Development","attr":{"id":"fc20e438-e7b9-4cca-be6a-49965daab528},"children":[]}]}]}, {"data":"Project Management","attr":{"id":"e1bdae71-6cfb-4e8c-ab29-a3eb03b9961d"},"children":[]} ] },
4.4Assemble JSON data, I use the method of first finding all parent nodes, i.e., parentid=1At that time, then recursively add all child nodes to the List<chiledren> object, and then assemble the infinite-level menu JSON data recursively through the loop. See the database data structure below
import java.util.List; public class Department { // Department ID private String departmentid; // Department name private String name; // Parent department ID private String parentid; //Sorting among the same level. The one with a smaller sorting ID is placed in front private String orders; //Child node 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 Here the servlet provides the json_data for the client. It is the json data that is called by ajax when initializing the control.
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(); //Here we call the method to create the tree node 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.6Let's take a look at the createTreeNode method in the above servlet.
Here is the core of creating json.
1)Firstly, get all the (parent=1)root node
@Override public StringBuilder createTreeNode() { //Create department collection List<Department> departments = new ArrayList<Department>(); //Place all root node department entities 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); "1".equals(departments.get(i).getParentid())){ json.deleteCharAt(json.length());-1); json.append(']'); json.append('}'); json.append(','); }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.How to create a node by right-clicking on the tree menu to pop up the add, remove, and other operations (you need to add the contextmenu plugin in the plugins, this example has it)
2.Bind the operation of jstree, here takes the addition of nodes as an example without listing one by one
Principle; By clicking the create button (contextMenu), which is the right-click pop-up button for selecting the tree node. Call the method shown in the figure above, the method in the figure above uses the POST method to request data from the background through AJAX, and save the created tree node to the database.
operation: The method of operation (create, remove, modify, etc.);
id: The ID of the current node, which is the parentID of the next node you create.
title: The name of the newly created node
With these data, you can retrieve data from the background and add it to the database.
4.8 Create a servlet to handle all operations (create, remove, modify, etc.)
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(); } /** * Servlet的doPost方法。<br> * * 此方法在表单的标签值方法等于时被调用 * post. * * @param request * the request sent by the client to the server * @param response * the response sent 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 } }
That's it, of course, the tree here can also be customized with icons, custom buttons, and other operations. The specifics can be explored on your own.
The above-mentioned is the source code for the implementation of the addition, deletion, modification, and query of the Bootstrap Jstree tree menu introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. I would also like to express my heartfelt gratitude to everyone for supporting the Nahan tutorial website!
Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)