项目需要,需动态生成tree,花了一早上时间才搞明白,自己比较笨,代码如下:
一、jsp页面中加入如下代码:
<ul id="pritree" class="easyui-tree" url="login/getTree.do?"> </ul>
二、后台代码如下:
首先定义结点类:
引自easyui-api:
树数据的格式(Tree data format)
每个节点可以包含下列特性:
· id:节点的 id,它对于加载远程数据很重要。
· text:显示的节点文字。
· state:节点状态, 'open' 或 'closed',默认是 'open'。当设为 'closed' 时,此节点有子节点,并且将从远程站点加载它们。
· checked:指示节点是否被选中。 Indicate whether the node is checked selected.
· attributes:给一个节点追加的自定义属性。
· children:定义了一些子节点的节点数组。
public class TreeNode implements Serializable{
private static final long serialVersionUID = 5184247463903594683L;
private String id;
private String text;
private String state;
private String iconCls;
private List<Object> children;
private Attribute attributes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getIconCls() {
return iconCls;
}
public void setIconCls(String iconCls) {
this.iconCls = iconCls;
}
public List<Object> getChildren() {
return children;
}
public void setChildren(List<Object> children) {
this.children = children;
}
public Attribute getAttributes() {
return attributes;
}
public void setAttributes(Attribute attributes) {
this.attributes = attributes;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TreeNode other = (TreeNode) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((id == null) ? 0 : id.hashCode());
return result;
}
}
其次,定义属性类:
public class Attribute implements Serializable{
private static final long serialVersionUID = -212707384862368309L;
private String priUrl;
public String getPriUrl() {
return priUrl;
}
public void setPriUrl(String priUrl) {
this.priUrl = priUrl;
}
}
在相应Action中添加List<TreeNode> treeNodeList数组,将自己相关的业务逻辑数据转化为 treeNodeList,struts配置文件如下:
<action name="getTree" class="backendLogManageAction" method="getTree"> <interceptor-ref name="scopedModelDriven"> <param name="scope">session</param> <param name="name">backOperatorDto</param> <param name="className">com.zline.common.dto.user.BackOperatorDto</param> </interceptor-ref> <interceptor-ref name="defaultStack"> </interceptor-ref> <interceptor-ref name="requestModel"></interceptor-ref> <result name="success" type="json"> <param name="root">treeNodeList</param> <param name="contentType">text/html</param> </result> </action>
这样既可在前台页面中动态生成树,下面是对树操作的两个小方法:
<script>
$(function(){
$("#pritree").tree({
onClick : function(node) {
var url = node.attributes.priUrl;
addTab(url,node.text);
},
onDblClick : function(node) {
$(this).tree('toggle', node.target);
}
});
});
</script>
具体方法可参看相关api