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

zTree和struts2 ajax实现树形菜单

不多说,直接给代码:

1、java代码:

@ParentPackage("json-default")
public class AjaxRuleConfigAction extends ActionSupport implements SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 10255L;

	// private List<String> operatorList = new ArrayList<String>();
	// private String columnName;
	private Map<String, Object> session;
	private String property;
	private String propertyType;
	private String tableName;

	// 存放节点信息
	private List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();

	/**
	 * 加载树形菜单
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/loadNode", results = { @Result(type = "json", name = SUCCESS) })
	public String doLoadNode() throws Exception {
		Object obj = session.get("database");
		if (obj == null) {
			return ERROR;
		}
		Database database = (Database) obj;
		/*** 根节点 ***/
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("id", database.getDatabaseName());
		rootMap.put("name", database.getDatabaseName());
		rootMap.put("isParent", true);// 设置是否为根节点
		List<Map<String, Object>> tableNode = new ArrayList<Map<String, Object>>();
		/*** 将数据库中的表作为第二级菜单 ***/
		Set<Table> tables = database.getTables();
		for (Table table : tables) {
			Map<String, Object> subNode = new HashMap<String, Object>();
			subNode.put("id", table.getTableName());
			subNode.put(
					"name",
					table.getFullName() == null ? table.getTableName() : table
							.getFullName());
			Set<Column> columns = table.getColumnSet();
			List<Map<String, Object>> columnNode = new ArrayList<Map<String, Object>>();
			/*** 将表中的列作为第三级菜单 ***/
			for (Column column : columns) {
				System.out.println(column.getFullName());
				Map<String, Object> thirdNode = new HashMap<String, Object>();
				thirdNode.put("id", column.getColumnName());
				thirdNode.put(
						"name",
						StringUtils.isEmpty(column.getFullName()) ? column
								.getColumnName() : column.getFullName());
				columnNode.add(thirdNode);
			}
			if (columnNode.size() != 0) {
				subNode.put("children", columnNode);
			}
			tableNode.add(subNode);
		}
		rootMap.put("children", tableNode);
		nodes.add(rootMap);
		return SUCCESS;
	}
.............
}

?2、页面的js代码:

var setting = {
	data : {
		simpleData : {
			enable : true,
			idKey : "id"
		}

	},
	callback : {
		//绑定树形菜单点击事件
		onDblClick : treeClick
	}
};
var zNodes;// 树节点,
var zTreeObj;// 树对象
$(function() {
	//页面加载时候发起ajax请求,获取树形菜单的数据
	$.ajax({
		url : "loadNode.action",
		type : "get",
		dataType : "json",
		global : false,
		async : false,
		success : function(data) {
			zNodes = eval(data.nodes);
		}
	});
	zTreeObj = $.fn.zTree.init($("#permission_tree"), setting, zNodes);
?