struts树的实现:包含jsp页面控件和js函数,还有Action中的提供树需要的数据的方法;
jsp页面:
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
<head>
<title></title>
<sx:head parseContent="true"/>
</head>
<body >
<div>
<div>
<sx:tree id="tree" rootNode="%{treeRootNode}"
childCollectionProperty="childList" nodeIdProperty="goodsCategoryId"
nodeTitleProperty="categoryName" treeSelectedTopic="treeSelected">
</sx:tree>
</div><br/>
<div id="displayId" style="float:left;padding-top: 20px;">
Please click on any of the tree nodes.
</div>
</div>
<script language="JavaScript" type="text/javascript">
dojo.event.topic.subscribe("treeSelected", function treeNodeSelected(node) {
dojo.io.bind({
url: "<s:url value='/to_edit_goods_category.action'/>?goodsCategoryId="+node.node.widgetId,
load: function(type, data, evt) {
var divDisplay = dojo.byId("displayId");
divDisplay.innerHTML=data;
},
preventCache:true,
mimeType: "text/html"
});
});
</script>
</body>
</html>
Action中获取树结构数据的方法:
public String getTreeRootNode() {
Category topNodeObj = new Category();
topNodeObj.setCategoryId(0);
topNodeObj.setCategoryName("分类");
List<Category> resultList = new ArrayList<Category> ();
List<Category> level1List = categoryConfigLogic.findCategoryByLevel(1);
List<Category> level2List;
List<Category> level3List;
List<Category> childList;
Category categoryLvl1;
Category categoryLvl2;
/**
* 获取2级和3级节点及属下各级节点数据
*/
for(int i=0;i<level1List.size();i++){
childList = new ArrayList<Category>();
categoryLvl1 = level1List.get(i);
level2List = categoryConfigLogic.findCategoryByParentId(categoryLvl1.getCategoryId());
for(int j=0;j<level2List.size();j++){
categoryLvl2 = level2List.get(j);
level3List = categoryConfigLogic.findCategoryByParentId(categoryLvl2.getCategoryId());
categoryLvl2.setChildren(level3List);
childList.add(categoryLvl2);
}
categoryLvl1.setChildren(childList);
resultList.add(categoryLvl1);
}
json=JSONArray.fromObject(resultList);
return SUCCESS;
}
//注释:该方法中把值转换成了json,在struts的树控件<sx:tree>是使用了json型的数据。
下面是Category实体类(用来存放树结构的数据):
public class Category implements java.io.Serializable {
// Fields
private Integer categoryId;
private String categoryName;
private Integer level;
private Integer parentId;
private Integer categoryIndex;
private String delFlg;
private Date createDate;
private Integer creator;
private Date lastUpd;
private Integer lastEditor;
private List<Category> children;
}
分析:树中需要的数据,是分为几层支点,就几层数据;层反映到实体中,就是List集合来实现的;一个实体中有一个List集合的属性,
这个List集合包含了一组低层的数据,低层中的数据的每个实体也会有List集合属性,这个属性又可以是一组更低层的数据。