tree后端实现

思维导图

 ①、实体类对象换成Json串->Json对象->方式一

JsonObject1 obj1=new JsonObject1("11", "学生管理", "closed");
		ObjectMapper om=new ObjectMapper();
		System.out.println("第一种:"+om.writeValueAsString(obj1));

实体类

package com.zking.demo;

public class JsonObject1 {
	/*
	 * {
		"id":11,
		"text":"学生管理",
		"state":"closed",
		"children":[{
			"id":111,
			"text":"Friend"
		}
	 */
	private String id;
	private String text;
	private String state;
	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 JsonObject1(String id, String text, String state) {
		super();
		this.id = id;
		this.text = text;
		this.state = state;
	}
	@Override
	public String toString() {
		return "JsonObject1 [id=" + id + ", text=" + text + ", state=" + state + "]";
	}
	public JsonObject1() {
		// TODO Auto-generated constructor stub
	}
	
	
}

②map集合转换成json串  

ObjectMapper om=new ObjectMapper();
Map<String, Object> map=new HashMap<String, Object>();
        map.put("id","11");
        map.put("text","xues");
        map.put("state", "closed");
        System.out.println(om.writeValueAsString(map));

①、实体类对象换成Json串->Json数组->

JsonObject1 obj1=new JsonObject1("14", "about.html", null);
		JsonObject1 obj2=new JsonObject1("15", "welcome.html", null);
		List<JsonObject1> list=new ArrayList<JsonObject1>();
		list.add(obj1);
		list.add(obj2);
		ObjectMapper om=new ObjectMapper();
		System.out.println("第一种:"+om.writeValueAsString(list));

②、Map集合换成Json串->Json数组->

Map< String, Object> map=new HashMap<String, Object>();
		map.put("id", "14");
		map.put("text", "about.html");
		map.put("state", null);
		Map< String, Object> map2=new HashMap<String, Object>();
		map2.put("id", "15");
		map2.put("text", "welcome.html");
		map2.put("state", null);
		List<Map<String, Object>> listMap=new ArrayList<>();
		listMap.add(map);
		listMap.add(map2);
		System.out.println("第二种:"+om.writeValueAsString(listMap));

 二.树形组件数据结构的生成

1.方法一

①.创建实体类

package com.zking.entity;

public class Menu {
private String serialNo;
private String menuid;
private String menuname;
private String menuURL;
private String parentid;
public String getSerialNo() {
	return serialNo;
}
public void setSerialNo(String serialNo) {
	this.serialNo = serialNo;
}
public String getMenuid() {
	return menuid;
}
public void setMenuid(String menuid) {
	this.menuid = menuid;
}
public String getMenuname() {
	return menuname;
}
public void setMenuname(String menuname) {
	this.menuname = menuname;
}
public String getMenuURL() {
	return menuURL;
}
public void setMenuURL(String menuURL) {
	this.menuURL = menuURL;
}
public String getParentid() {
	return parentid;
}
public void setParentid(String parentid) {
	this.parentid = parentid;
}
@Override
public String toString() {
	return "Menu [serialNo=" + serialNo + ", menuid=" + menuid + ", menuname=" + menuname + ", menuURL=" + menuURL
			+ ", parentid=" + parentid + "]";
}
public Menu(String serialNo, String menuid, String menuname, String menuURL, String parentid) {
	super();
	this.serialNo = serialNo;
	this.menuid = menuid;
	this.menuname = menuname;
	this.menuURL = menuURL;
	this.parentid = parentid;
}
public Menu() {
	super();
}


}

2.MenuDao

package com.zking.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zking.entity.Menu;
import com.zking.util.BaseDao;
import com.zking.util.BuildTree;
import com.zking.util.PageBean;
import com.zking.util.TreeVo;

public class MenuDao extends BaseDao<Menu>{
public List<Menu> list(Menu menu,PageBean pageBean) throws Exception{
	return super.executeQuery("select * from t_easyui_menu", Menu.class, pageBean);
	
}
public List<TreeVo<Menu>> tree(Menu menu,PageBean pageBean) throws Exception{
	//拿到的是平级,没有父子关系的数据
	List<Menu> list=this.list(menu, pageBean);

//	List<Menu>-->List<TreeVo<Menu>>
	List<TreeVo<Menu>> listVos=new ArrayList<TreeVo<Menu>>();
	for (Menu m : list) {
		TreeVo<Menu> vo=new TreeVo<>();
		vo.setId(m.getMenuid());
		vo.setText(m.getMenuname());
		vo.setParentId(m.getParentid());
		Map<String, Object> attributes=new HashMap<String, Object>();
		//self是个键名字,随便取个名字
		//node.attributes.self.menuURL
	     attributes.put("self", m);
	     vo.setAttributes(attributes);
	listVos.add(vo);
	}
	//构建父子层级关系(希望拿到菜单下所有子节点数据)
	
	return BuildTree.buildList(listVos, "000");
	
}

public static void main(String[] args) throws Exception {
	MenuDao menuDao=new MenuDao();
//	List<Menu> list=menuDao.list(null, null);
    List<TreeVo<Menu>> tree=menuDao.tree(null, null);
	
	ObjectMapper om=new ObjectMapper();
     /*
      * 缺陷:
      * 1.json串并没有体现出父子层级关系,数据之间都是平级的
      * 2.json串属性并不是id/text...等easyui要求的属性
      * 
      * 思考:
      * TreeVo<T>对象
      * id:节点ID,对加载远程数据很重要。
      * text:显示节点文本。
      * state:节点状态,'open'或'closed',默认:'open'。如果为'closed'的时候,将不自动展开该节点。
      * checked:表示该节点是否被选中。
      * attributes:被添加到节点的自定义属性。
      * children:一个节点数组声明了若干节点。
      * 
      * 2List<Menu>-->List<TreeVo<Menu>>
      * TreeVo vo=new TreeVo();
      * vo.setid(menu.getId());
      * vo.setText(menu.getmenunaem());
      * 
      * 3.让List<TreeVo<Menu>>中的数据有父子层级关系
      * 
      * 
      */
//     for() {
    	 // 外层
    	 /*
    	  * 权限管理
    	  * for(){
    	  *   内层
    	  * }
    	  */
    	 
//     }
     
//     System.out.println(om.writeValueAsString(list));
	System.out.println(om.writeValueAsString(tree));
	
}
}

TreeVo

package com.zking.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class TreeVo<T> {
	/**
	 * 节点ID
	 */
	private String id;
	/**
	 * 显示节点文本
	 */
	private String text;
	/**
	 * 节点状态,open closed
	 */
	private Map<String, Object> state;
	/**
	 * 节点是否被选中 true false
	 */
	private boolean checked = false;
	/**
	 * 节点属性
	 */
	private Map<String, Object> attributes;

	/**
	 * 节点的子节点
	 */
	private List<TreeVo<T>> children = new ArrayList<TreeVo<T>>();

	/**
	 * 父ID
	 */
	private String parentId;
	/**
	 * 是否有父节点
	 */
	private boolean hasParent = false;
	/**
	 * 是否有子节点
	 */
	private boolean hasChildren = false;

	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 Map<String, Object> getState() {
		return state;
	}

	public void setState(Map<String, Object> state) {
		this.state = state;
	}

	public boolean isChecked() {
		return checked;
	}

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

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

	public List<TreeVo<T>> getChildren() {
		return children;
	}

	public void setChildren(List<TreeVo<T>> children) {
		this.children = children;
	}

	public boolean isHasParent() {
		return hasParent;
	}

	public void setHasParent(boolean isParent) {
		this.hasParent = isParent;
	}

	public boolean isHasChildren() {
		return hasChildren;
	}

	public void setChildren(boolean isChildren) {
		this.hasChildren = isChildren;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public TreeVo(String id, String text, Map<String, Object> state, boolean checked, Map<String, Object> attributes,
                  List<TreeVo<T>> children, boolean isParent, boolean isChildren, String parentID) {
		super();
		this.id = id;
		this.text = text;
		this.state = state;
		this.checked = checked;
		this.attributes = attributes;
		this.children = children;
		this.hasParent = isParent;
		this.hasChildren = isChildren;
		this.parentId = parentID;
	}

	public TreeVo() {
		super();
	}

}

BuildTree

package com.zking.util;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildTree {

	/**
	 * 默认-1为顶级节点
	 * @param nodes
	 * @param <T>
	 * @return
	 */
	public static <T> TreeVo<T> build(List<TreeVo<T>> nodes) {

		if (nodes == null) {
			return null;
		}
		List<TreeVo<T>> topNodes = new ArrayList<TreeVo<T>>();

		for (TreeVo<T> children : nodes) {
			String pid = children.getParentId();
			if (pid == null || "-1".equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (TreeVo<T> parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);
					continue;
				}
			}

		}

		TreeVo<T> root = new TreeVo<T>();
		if (topNodes.size() == 1) {
			root = topNodes.get(0);
		} else {
			root.setId("000");
			root.setParentId("-1");
			root.setHasParent(false);
			root.setChildren(true);
			root.setChecked(true);
			root.setChildren(topNodes);
			root.setText("顶级节点");
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			root.setState(state);
		}

		return root;
	}

	/**
	 * 指定idparam为顶级节点
	 * @param nodes
	 * @param idParam
	 * @param <T>
	 * @return
	 */
	public static <T> List<TreeVo<T>> buildList(List<TreeVo<T>> nodes, String idParam) {
		if (nodes == null) {
			return null;
		}
		List<TreeVo<T>> topNodes = new ArrayList<TreeVo<T>>();

		for (TreeVo<T> children : nodes) {

			String pid = children.getParentId();
			if (pid == null || idParam.equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (TreeVo<T> parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);

					continue;
				}
			}

		}
		return topNodes;
	}

}

js文件

$(function(){
	/*
	 * 1.tree方法时通过$.extends()拓展出来的
	 * 2.tree方法做的事情
	 * $('#tt').append("<li><span>File21</span>  </li>")
	 * .append("<li><span>File21</span>  </li>");
	 * 
	 * 需求:
	 * 1.点击左侧显示右侧tab
	 *   1.1给菜单添加点击事件
	 *    1.2调用tabs选项卡打开对应的页面
	 *    选项卡
	 *     选项卡对应页面展示
	 * 
	 * 2.不能打开重复的tab
	 *   拿到目前所有打开的tabs选项卡,与就要打开的选项卡做对比(exists)
	 *    存在ture:不打开
	 *    存在false:打开  
	 * 3.对于已经存在的tab选项,被点击时应该默认被选中
	 * 4.点击菜单,能够访问 对应的页面,而非文字内容
	 * 
	 * 注意:js文件中,是不支持el表达式
	 */
	$('#stumenu').tree({    
	    url:$("#ctx").val()+'/menu.action?methodName=tree', 
	  
	    onClick: function(node){
	    	  alert(url)
//			alert(node.text);  // 在用户点击的时候提示
			// add a new tab panel
	    	//判断当前将要打开的选项卡是否存在
	    	var exists=$('#stutabs').tabs('exists',node.text);;
	    	if(exists){
	    		$('#stutabs').tabs('select',node.text)
	    	}else{
	    		$('#stutabs').tabs('add',{    
				    title:node.text,    
				    content:'<iframe width="100%" height="100%" src="'+node.attributes.url+'"></iframe>',    
				    closable:true,    
				    tools:[{    
				        iconCls:'icon-mini-refresh',    
				        handler:function(){    
				            alert('refresh');    
				        }    
				    }]    
				});  
	    	}
	    	
	    	
			
	    }
	});  
})

index.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>书籍后管主界面</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">   
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/icon.css">   
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>   
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/index.js"></script>
</head>


<body class="easyui-layout">   
<input tyep="hidden" id="ctx" value="${pageContext.request.contextPath}">
    <div data-options="region:'north',title:'网上书城',split:true" style="height:100px;"></div>   
    <div data-options="region:'south',title:'版权/链接',split:true" style="height:100px;"></div>   
    <!-- <div data-options="region:'east',iconCls:'icon-reload',title:'East',split:true" style="width:100px;"></div>    -->
    <div data-options="region:'west',title:'菜单管理',split:true" style="width:200px;">
    
    <!-- 
    缺陷:1.样式缺陷
       2.不好做数据的渲染,树形结构的动态显示(重点)
    
     -->
    
    
	<ul id="stumenu"></ul>  
    
    </div>   
    <div data-options="region:'center',title:'内容区'" style="padding:5px;background:#eee;">
    <div id="stutabs" class="easyui-tabs" style="width:100%;height:100%;">   
  
</div>  
    </div>   
</body>  


</html>

ResponseUtil

package com.zking.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ResponseUtil {

	public static void write(HttpServletResponse response,Object o)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
	public static void writeJson(HttpServletResponse response,Object o)throws Exception{
		ObjectMapper om=new ObjectMapper();
		//om.writeValueAsString(o) 代表了json串
		write(response, om.writeValueAsString(o));
	}
}

MenuAction(子控制器)

package com.zking.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zking.dao.MenuDao;
import com.zking.entity.Menu;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
import com.zking.util.TreeVo;

public class MenuAction extends ActionSupport implements ModelDriver<Menu> {
private Menu menu=new Menu();
private MenuDao menuDao=new MenuDao();

@Override
public Menu getModel() {
	return menu;
}
	public String tree(HttpServletRequest req, HttpServletResponse resp) {
		 try {
			List<TreeVo<Menu>> tree=menuDao.tree(null, null);
		    ResponseUtil.writeJson(resp,tree);
		 } catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		}
	
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>T269_easyui</display-name>
  
<servlet>

<servlet-name>mvc</servlet-name>

<servlet-class>com.zking.framework.DispatchServlet</servlet-class>


<init-param>

<param-name>configurationLocation</param-name>

<param-value>/mvc2.xml</param-value>

</init-param>

</servlet>


<servlet-mapping>

<servlet-name>mvc</servlet-name>

<url-pattern>*.action</url-pattern>

</servlet-mapping>
</web-app>

mvc2.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/blog" type="com.zking.web.BlogAction">
		<forward name="list" path="/blogList.jsp" redirect="false" />
		<forward name="toList" path="/blog.action?methodName=list" redirect="true" />
		<forward name="toEdit" path="/blogEdit.jsp" redirect="false" />
	</action>
	<action path="/menu" type="com.zking.web.MenuAction">
	</action>
</config>

所有jar包

 

运行结果

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值