从 java 为给定文件夹 x 级别创建 jstree 数据

Creation of jstree data from java for a given folder x levels down

给定一个文件夹,我想构建下至 x 层的子树并呈现为 jstrees html 格式(即 ul、li 等等)https://www.jstree.com/docs/html/ 以便可以查看服务器文件通过网络浏览器远程访问。

最好的方法是什么?

有没有人创建了一个 lib tieing java 和 jstree 来做到这一点,看来我不是第一个想要这样做的人。

只是为了澄清你的问题:

  • 您在服务器上有一个 Java 应用程序 运行。
  • Java 应用程序用于呈现在网络浏览器中查看的网页。
  • 您想使用 jsTree,一个 Java 脚本库,为您的客户呈现漂亮的树。
  • 您希望 jsTree 显示服务器上某些文件夹的结构。

jsTree 是一个 javascript 库,因此,您必须在解决方案的某处执行 Java 脚本。虽然 Java 肯定有可能执行 Java 脚本(Rhino 看起来很有希望),但浏览器似乎是最自然的地方。

jsTree如何接受输入?从网站上看,它表示它支持 Ajax 和 JSON。 JSON 当然可以通过渲染页面的服务器应用程序嵌入到页面中,所以这看起来很合适。

于是解决方案出现了。您的 Java 服务器应用呈现页面。在呈现页面时,它包含 jsTree 库,并且嵌入了一个 JSON 文档,其中包含您希望客户端看到的服务器端文件夹的结构信息。

客户端浏览器中的

Javascript 运行 将嵌入的 json 数据馈送到 jsTree,你会得到一个漂亮的图表。

首先,我想指出 jsTree 也接受 JSON 作为数据输入,而不仅仅是原始的 html(https://www.jstree.com/docs/json/)

看起来像这样:

// Expected format of the node (there are no required fields)
{
  id          : "string" // will be autogenerated if omitted
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  children    : []  // array of strings or objects
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}

要生成这样的 JSON 格式(或 HTML 格式中的等效格式)可以使用递归函数相当轻松地完成。这是伪代码:

class Node {
  String id;
  String text;
  // ...
  List<Node> children;
}

class Filesystem {

   Node browse(File path, int depth) {
       Node node = new Node(file);
       if( depth > 0 ) {
          for(File f : file.listFiles()) {
             Node child = browse(f, depth - 1);
             node.children.add(child);
          }
       }
       return node;
   }
}

这不是复制粘贴解决方案,但它应该相当直接地获得一个。