JsTree-JAVAを使用した単純なツリーの構築

こんにちはHabr! これは、Webプログラミングの初心者向けの私の最初の投稿です。 必要な知識:



-Java;

-サーブレットの作成方法を知っている。

-HTML;

-JavaScript;

-jQuery。



タスクはこれでした:



-Webページ上にツリーを構築するデータベースデータに基づいて、データが多すぎるため、ツリー全体をすぐにロードできませんでした。



私の投稿では、JSON形式のAjaxを使用して、サーブレットとJsTreeプラグインを使用してツリーを構築する方法の簡単なステップバイステップの例を示します。データは単純なアルゴリズムを使用して生成されます。



すべてのコードはGitHubで利用でき、 Herokuでデプロイされたバージョンも利用できます。







モデル



データベーステーブルには{"id"、 "parentId"、 "text"}などのレコードがありました。このデータタイプにはJsTreeプラグインが理想的です。 JsTreeは、次の形式のデータを理解します。



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





実際、別の子供フィールドが必要であることがわかりました。 常にtrueにする必要があります。要素に子がない場合でも問題ありません。 ajaxリクエストの後、プラグインはこれを理解し、矢印を削除します。



最初にモデルが必要です:



 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; } }
      
      





データをJSONに変換する方法を理解する価値があるので、個人的にFasterXML / jackson-coreを使用しました 。 このために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>
      
      





そして、変換のためのメソッド自体:



 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()); } }
      
      





メソッドを機能させるには、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; } }
      
      





素晴らしい、モデルがあり、データが必要になりました。



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; } }
      
      





コントローラー



ここで、親ノードのIDを取得し、JSON形式で子を提供するサーブレットが必要です。



 @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(); } }
      
      





次に、パフォーマンスを確認する必要があります。プロジェクトを組み立てる必要があります。 実際、これは最も簡単なことではありませんが、重要ではありません。 ロシア語には優れたステップバイステップの説明があります。



プロジェクトを組み立て、サーブレットを使用すると次のように表示されます。







奇数の親-子なし:







偶数-9個:







Web



さて、これは小さなものです。この奇跡をページに埋め込みます。 これを行うには、 JqueryJsTreeをダウンロードします。



 <!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>
      
      





ご清聴ありがとうございました。誰かが何か役に立つものを描いてくれることを願っています。



All Articles