Java实现数据库构建树形
根据数据库中数据结构来构建树形,至少需要三个字段。
ParentID:指的是该节点的节点id;
SonID:指的是该节点的父节点id;
NodeName:节点的名称。
如下图可见第二条和第三条数据的SonID是第一条数据的ParentID,因此节点1和节点2的父节点是0。
数据库录入数据后,接下来需要一个方法将数据传递给jsp,方法中先创建一个list集合,list集合内的对象是一个map集合,再查询出数据库中的树形表,使用foreach将ParentID、SonID、NodeName放入map集合再放入list集合中,传递给jsp。
private void SelectCustomerClassificationTree(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/json;charset=utf-8");
List<Map<String, Object>> jsonlist = new ArrayList<Map<String, Object>>();
PrintWriter out = response.getWriter();
List<CustomerTree> CustomerTree = Service.SelectCustomerTree();
for(CustomerTree customertree: CustomerTree){
Map<String, Object> jsonobj = new HashMap<String, Object>();
jsonobj.put("id", customertree.getCustomerParentID());//节点id
jsonobj.put("pId", customertree.getCustomerSonID());//父节点id
jsonobj.put("name", customertree.getCustomerNodeName());//节点名称
jsonlist.add(jsonobj);
}
out.write(ToJsonUtil.toJson(jsonlist));
}
在jsp中需引用zTree_v3插件,zTree_v3.jar百度云下载链接;提取码:f1gp。
构建树形代码如下:
<script>
$(function(){
$.ajax({
type:"Get",
url:"${ctx}/servlet/MainServlet?type=SelectCustomerClassificationTree",
async:false,
success:function (d) {
$.fn.zTree.init($("#treeDemo"), setting, d.data);
}
});
});
var setting = {
check: {
enable: false,
chkStyle: "checkbox",
chkboxType: { "Y": "ps", "N": "ps" },
isSimpleData: true,//数据是否采用简单 Array 格式,默认false
treeNodeKey: "id",//在isSimpleData格式下,当前节点id属性
treeNodeParentKey: "pId",//在isSimpleData格式下,当前节点的父节点id属性
showLine: true, //是否显示节点间的连线
checkable: true
},
data: {
simpleData: {
enable: true
}
},
callback: {
onClick: zTreeOnClick
}
};
//popZtree(setting);
function zTreeOnClick(event, treeId, treeNode) {
alert(treeNode.tId + "," + treeNode.treeNode);
};
</script>
Jsp页面内容如下:
<body>
<div class="zTreeDemoBackground">
<ul id="treeDemo" class="ztree"></ul>
</div>
</body>
树形实现图: