给定一个文件夹,我想构建一个低至x级别的子树,并呈现为jstrees html格式(即ul,li等)https://www.jstree.com/docs/html/,以便可以通过webbrowser远程查看服务器文件。
这样做的最佳方式是什么?
有没有人创建了一个用java连接java和jstree的lib,似乎我不能成为第一个想要这样做的人。
答案 0 :(得分:2)
首先,我想指出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;
}
}
它不是一个复制粘贴解决方案,但要获得一个解决方案应该相当直接。
答案 1 :(得分:1)
只是为了澄清你的问题:
jsTree是一个javascript库,因此,在解决方案的某个地方你必须执行Javascript。虽然Java当然可以执行Javascript(Rhino看起来很有希望),但看起来浏览器似乎是最自然的地方。
jsTree如何接受输入?从网站上,它表明它支持Ajax和JSON。当然,JSON可以通过呈现页面的服务器应用程序嵌入到页面中,因此这看起来非常合适。
然后出现一个解决方案。您的Java服务器应用程序呈现页面。在渲染页面时,它包含jsTree库,它嵌入了一个JSON文档,其中包含您希望客户端看到的服务器端文件夹的结构信息。
在客户端浏览器中运行的Javascript将嵌入的json数据提供给jsTree,你得到了一个漂亮的图表。