📜 ⬆️ ⬇️

JsTree - building a simple tree using JAVA

Hi Habr! This is my first post, which is designed for newcomers to web programming. Knowledge required:

- Java;
- Know how to create a servlet;
- HTML;
- javascript;
- jQuery.

The task was as follows:
')
- On the basis of the database data to build a tree on a web page, the entire tree could not be immediately loaded as too much data.

In my post I will show you a small step-by-step example of how to build a tree using a servlet and a JsTree plugin, using Ajax in JSON format, the data will be generated using a simple algorithm.

All code is available on GitHub , as well as a detailed version on Heroku .



Model


In the database table there were records of the type {"id", "parentId", "text"}, the JsTree plugin is ideal for this type of data. JsTree understands data in this format:

{ id : "string" // required parent : "string" // required text : "string" // node text icon : "string" // string for custom } 

In fact, it turned out that we need another field children. You should always put true in it, it's okay if the element has no children. After the ajax request, the plugin will understand and remove the arrow.

First we need a model:

 public class Node { private String id; private String parent; private String text; private boolean children; public Node(String id, String parent, String text) { this.id = id; this.parent = parent; this.text = text; this.children = true; } } 

Now it's worth figuring out how to convert data to JSON, I personally used FasterXML / jackson-core . To do this, add dependencies to maven:

 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.2.2</version> </dependency> 

And the method itself for converting:

 import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class ConverterJSON { public static String toJSON_String(Map map) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(map.values()); } } 

In order for the method to work, you need to place annotations in Node:

 import com.fasterxml.jackson.annotation.JsonProperty; public class Node { @JsonProperty("id") private String id; @JsonProperty("parent") private String parent; @JsonProperty("text") private String text; @JsonProperty("children") private boolean children; public Node(String id, String parent, String text) { this.id = id; this.parent = parent; this.text = text; this.children = true; } public String getId() { return id; } } 

Great, we have a model, now we need data.

DAO


 public interface Data { public Map getRoot(); public Map getById(String parentId); } 

 import java.util.HashMap; import java.util.Map; //  public class LocalDataImpl implements Data { public static final int MAX_ELEMENT = 10; private static LocalDataImpl ourInstance = new LocalDataImpl(); public static LocalDataImpl getInstance() { return ourInstance; } private LocalDataImpl() { } @Override public Map getRoot() { //      10  Map result = new HashMap(); for (int i = 1; i < MAX_ELEMENT; i++) { Node node = new Node(Integer.toString(i),"#","Node "+i); //   JsTree    = "#" result.put(node.getId(),node); } return result; } @Override public Map getById(String parentId) { //       10 ,           Map result = new HashMap(); if (Integer.parseInt(parentId)%2==0) for (int i = 1; i < MAX_ELEMENT; i++) { String newId = parentId+Integer.toString(i); Node node = new Node(newId, parentId,"Node "+newId); result.put(node.getId(),node); } return result; } } 

Controller


Now we need a servlet that will accept the node id of the parent, and give the children in JSON format:

 @WebServlet(urlPatterns = {"/ajax"}) public class AjaxTree extends HttpServlet { private Data data; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json; charset=utf-8"); String nodeId = request.getParameter("id"); PrintWriter out = response.getWriter(); try{ if (nodeId.equals("root")) out.println(ConverterJSON.toJSON_String(data.getRoot())); else out.println(ConverterJSON.toJSON_String(data.getById(nodeId))); }catch (IOException e) {e.printStackTrace();} finally { out.close(); } } @Override public void init() throws ServletException { super.init(); data = LocalDataImpl.getInstance(); } } 

Now you need to check its performance, you need to build a project. In fact, it turns out that this is not a simple matter, but it does not matter, there is an excellent step-by-step instruction in Russian .

Collected the project and when using our servlet we see:



Odd parent - no children:



Even - 9 pieces:



Web


Now it's small, we will embed this miracle in the page. For this you need to download Jquery and JsTree .

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> </title> <link rel="stylesheet" href="themes/default/style.min.css" /> </head> <body> <!--  Jquery --> <script src="js/jquery-2.1.1.min.js"></script> <!--  JsTree--> <script src="js/jstree.min.js"></script> <!--    --> <script> $(function () { $('#jstree') .jstree({ "plugins": [ "sort", "json_data" ], 'core': { 'data': { 'url': function (node) { return node.id === '#' ? 'ajax?id=root' : 'ajax?id=' + node.id; <!--       ,  --> }, 'data': function (node) { return { 'id': node.id }; } } } }); }); </script> <div id="jstree"></div> <!--     --> </body> </html> 

Thank you for your attention, I hope someone will get something useful.

Source: https://habr.com/ru/post/313208/


All Articles