而我电脑上的文件组织就和显示的一样:
[{
"id":1,"text":"Root node","children":[
{"id":2,"text":"Child node 1","children":true},
{"id":3,"text":"Child node 2"}
]
}]
看到了吧,id为2的item的children属性是true,这说明什么?说明这个item下面还有文件/文件夹
OK,现在上我写的例子:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
标题
@WebServlet( urlPatterns = "/ShowIndex")
public class ShowIndexServlet extends HttpServlet {
/**
* https://github.com/vakata/jstree
*/
private static final long serialVersionUID = -3867365983209162571L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
String result="";
String id=request.getParameter("id");
// System.out.println("i get id "+id);
// public static final String PLANT_LOCATION="E:\\plant";
// public static final String PARENT_LOCATION="E:\\";
if (id.equals("#")) {
result=ShowFiles.getChildrenFiles(Config.PLANT_LOCATION);
}else{
// id = new String (id.getBytes("iso-8859-1"), "UTF-8") ;
result=ShowFiles.getChildrenFiles(Config.PARENT_LOCATION+id);
}
out.write(result);
out.flush();
out.close();
}
}
注意:因为我的目录上有中文,本来是使用id = new String (id.getBytes("iso-8859-1"), "UTF-8") ; 来做转换的,后来发现tomcat路径中文问题直接在server.xml的Connector里加上 URIEncoding="utf-8"即可:
public class ShowFiles {
public static String getChildrenFiles(String parentPath) {
JSONArray list = new JSONArray();
File file = new File(parentPath);
File[] tempList = file.listFiles();
// System.out.println("该目录下对象个数:" + tempList.length);
String fileName="";
for (int i = 0; i < tempList.length; i++) {
JSONObject item = new JSONObject();
if (tempList[i].isFile()) {
// System.out.println("文 件:" + tempList[i]);
//为什么substring(3) 因为我去掉了盘符
item.put("id", tempList[i].toString().substring(3));
//每一个item都有哪些属性?自己去git上看吧
item.put("icon", "images/icon.png");
fileName=tempList[i].getName();
item.put("text", fileName.substring(0,fileName.lastIndexOf(".")));
}
if (tempList[i].isDirectory()) {
// System.out.println("文 件夹:" + tempList[i]);
item.put("id", tempList[i].toString().substring(3));
item.put("text", tempList[i].getName());
//如果是文件夹 children就是true
item.put("children", true);
}
list.add(item);
}
// System.out.println(list);
return list.toString();
}
}
看到上面的代码,大家应该明白了,列表里每个item的id就是这个文件/文件夹的全地址(我去掉了盘符),text(就是在页面上显示的内容)是文件名
//点击任何一个item就会调用下面的的代码
$('#container').on("changed.jstree", function (e, data) {
var name=String(data.selected); //必须得转换成字符串
// alert(name);
if(name.search("jpg")>1||name.search("png")>1){
$("#plant").attr("src",name);
}
});
});
如果item的id里面包含了jpg或者png我就认为它是图片
https://www.jstree.com/api/
项目使用的js/与css如下:
http://pan.baidu.com/s/1jIqaJLc