日期:2014-05-16  浏览次数:20386 次

easyui struts后台实现tree返回json数据

首先jsp页面有一ul用于展现tree

<ul id="trueULid"></ul>

加载tree

<script type="text/javascript">
$(function() {
   $('#trueULid').tree( {
	 url : 'admin/HhTestTree.do'
   });
});
</script>

配置action
<action name="HhTestTree" method="testTree"
	class="org.bkgd.ehome.jeeplugin.message.web.action.ActionHhMessageTypeQuery">
	<result type="json">
		<param name="root">testTreeNodes</param>
	</result>
</action>

需要封装对象tree
public class TestTreeNode implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String id;
	private String text;
	private String state = "open";
	private boolean checked;

	public TestTreeNode(String id, String text, String state, boolean checked) {
		this.id = id;
		this.text = text;
		this.state = state;
		this.checked = checked;
	}
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}
}

表结构如图

首先查询所有parentid为NONE的数据(测试数组件的ID为null)然后同时判断该节点下是否有子节点,
如果有则状态是关闭状态
当继续展开树的时候 会将该ID值传入,然后查询该节点的子节点。


action方法实现

private List<TestTreeNode> testTreeNodes = new ArrayList<TestTreeNode>();
private String id;// 树组件使用的ID

public String testTree() {
	try {
		List<Map<String,Object>> list = aloneIMP.getTreeNodes(id).search().getResultList();
		for(Map<String,Object> m:list){
			//判断是否有子节点
			List<Map<String,Object>> isHasChildren = aloneIMP.getTreeChildren(null).addUserWhere(" and parentid ='"+(String)m.get("ID")+"'").search().getResultList();
			if(isHasChildren.size()==0){
				testTreeNodes.add(new TestTreeNode((String)m.get("ID"),(String)m.get("NAME"),"open",false));	
			}else{
				testTreeNodes.add(new TestTreeNode((String)m.get("ID"),(String)m.get("NAME"),"closed",false));
			}
					
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return SUCCESS;
}

此方法不具公共性,是自己的一些封装实现。主要是如何进行查询节点,

getTreeNodes()的实现方法为:

@Override
public DataQuery getTreeNodes(String id) {
	if(id==null){
		dbQuery = DataQuery
		.init(
				query,
				"hh_message_type",
				"ID,STATE,PARENTID,NAME,TITLE").addUserWhere(" and parentid = 'NONE'");
	}else{
		dbQuery = DataQuery
		.init(
				query,
				"hh_message_type",
				"ID,STATE,PARENTID,NAME,TITLE").addUserWhere(" and parentid = '"+id+"'");
	}
	
	return dbQuery;
}

getTreeChildren()的实现方法为:

@Override
	public DataQuery getTreeChildren(DataQuery query) {