这个树是用zTree这个插件搞定的!代码如下
页面代码:
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>jQuery Tree </title>
<link rel="stylesheet" href="zTree/demoStyle/demo.css" type="text/css">
<link rel="stylesheet" href="zTree/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="zTree/jquery-1.4.2.js"></script>
<script type="text/javascript" src="zTree/jquery.ztree-2.6.js"></script>
<SCRIPT LANGUAGE="JavaScript">
var zTree1;
var setting = {
checkable: false,
async: true,
asyncUrl: "Tree", //获取节点数据的URL地址
asyncParam: ["name", "id"], //获取节点数据时,必须的数据名称,例如:id、name
asyncParamOther: ["test","true"] , //其它参数 ( key, value 键值对格式)
callback : {
click: function (event, treeId, treeNode){
// zTree1.expandNode(treeNode, true, false);
} ,
expand : function (event, treeId, treeNode){
},
collapse:function (event, treeId, treeNode){
}
}
};
function refreshTree() {
zTree1 = $("#treeDemo").zTree(setting );
}
$(document).ready(function(){
refreshTree();
});
</SCRIPT>
</HEAD>
<BODY>
<ul id="treeDemo" class="tree" style="height:500px;width:300px;"></ul>
</BODY>
</HTML>
java代码:
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class Tree extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String pId = request.getParameter("id");
String pName = request.getParameter("name");
//延迟,让loading 显示出来
for (int i = 0; i < 9999; i++) { }
//构造数据,可以从数据库中查询
String str = "[" ;
if (pId == null || pName == null){
pId = "0";
pName = "";
str += "{'id':'root','name':'根节点','icon':'"+request.getContextPath()+"/zTree/logout.jpg','isParent':true},";
}else {
for (int i = 1; i < 3 ; i++) {
String nId = pId + i;
String nName = nId;
str += "{'id':'"+nId + "','name':'"+nName + "','icon':''" + ",'isParent':" + (i % 2 == 0 ? false:true) + "},";
}
}
str = str.substring(0,str.length()-1) + "]";
reponse(request,response,str );
} catch (Exception e) {
e.printStackTrace();
}
}
public void reponse(HttpServletRequest request, HttpServletResponse response,Object msg) throws Exception{
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(msg.toString());
out.flush();
out.close();
}
}
这篇博客是因为以为网友提出的,所以就做了这个demo,这个也是根据zTree例子中的一个改写的,同志们如果这个插件感兴趣,可以仔细阅读源码、例子和api文档!