Tree 后端实现

思维导图~~~

 一、Json串的转换

{
    "id":11,
    "text":"学生管理",
    "state":"closed",
    "children":[{
        "id":111,
       "text":"Friend"
    }

 

1、实现以上代码

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

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

实体类:

 

 

②、Map集合换成Json串->Json对象->方式二

Map< String, Object> map=new HashMap<String, Object>();
		map.put("id", "11");
		map.put("text", "学生管理");
		map.put("state", "closed");
		System.out.println("第二种:"+om.writeValueAsString(map));

③、 推荐使用第一种, 建议创建一个对象,做字符串的转换,
       不创建,会简便代码,但是可能出现误写,导致代码全错

④、结果

2、实现以下代码 

    [{
       "id":14,
       "text":"about.html"
    },{
        "id":15,
       "text":"welcome.html"
    }]

①、实体类对象换成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、导入相关jar包

①、web_xml进行配置

②、 显示所有类

 

 2、在com.mwy.util中加入·TreeVo<T>类、BuildTree类

①、TreeVo<T>类

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类

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;
	}

}

3、根据属性创建实体类(与数据库一致)

package com.mwy.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;
	}
	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() {
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Menu [serialNo=" + serialNo + ", menuid=" + menuid + ", menuname=" + menuname + ", menuURL=" + menuURL
				+ ", parentid=" + parentid + "]";
	}	
}

4、MenuDao extends BaseDao<Menu>

①、tree服务台打印的结果用:https://tool.oschina.net/codeformat/json/   在线代码格式化

package com.mwy.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.mwy.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 {
		//1、拿到的是平级,没有父级层级关系的数据
		List<Menu> list=this.list(menu, pageBean);
		//2、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是个键名字,随便取名字
			attributes.put("self", m);
			vo.setAttributes(attributes);
			listvos.add(vo);
		}
		//构建父子层级关系(希望拿到菜单管理下的所有子节点数据)
		return BuildTree.buildList(listvos, "000");
	}
	public static void main(String[] args) throws Exception {
		MenuDao md=new MenuDao();
		//List<Menu> list = md.list(null, null);

		List<TreeVo<Menu>> tree = md.tree(null, null);
		ObjectMapper om=new ObjectMapper();
  }
		//System.out.println(om.writeValueAsString(list));

		System.out.println(om.writeValueAsString(tree));
	}
}

②、 在线代码格式化后,将代码加入tree_data1.json数据中

5、MenuAction extends ActionSupport implements ModelDriver<Menu>

返回值因为是ajax,所以不需要配置mvc2.xml,返回值直接就是null

package com.mwy.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mwy.dao.MenuDao;
import com.mwy.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 md=new MenuDao();
	
	@Override
	public Menu getModel() {
		// TODO Auto-generated method stub
		return menu;
	}
	public String tree(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		List<TreeVo<Menu>> tree = md.tree(null, null);
		ResponseUtil.writeJson(resp, tree);
		return null;
	}
}

上述代码调用方法的类

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));	
	}	
}

6、使用File处理来自WebContent的JSON数据。

$(function() {
	/**
	 * 1、tree 方法是通过$.extends()拓展出来的
	 * 2、tree方法做的事情
	 *   $('#tt').append("<li><span>File 12</span> </li>");
	 *   
	 *   需求:
	 *   1、点击左侧显示右侧Tab
	 *       1.1给菜单添加点击事件
	 *       1.2调用tabs选项卡打开对应的页面
	 *           选项卡打开
	 *           选项卡对应页面展示
	 *       1.3新建对应的打开页面
	 *   2、不能打开重复的Tab
	 *       拿到目前所有打开的tabs选项卡,与将要打开的选项卡做对比(exists)
	 *       存在true:不打开;存在false:打开
	 *   3、对于已经存在的Tab选项,被点击的时候应该默认被选中
	 *   4、点击菜单,能够访问对应的页面,而非文字内容
	 *    
	 *    注意:js文件中,是不支持el表达式
	 */
	$('#stuMenu').tree({   
 
	    url:$("#ctx").val()+'/menu.action?methodName=tree' ,
	    
	    onClick:function(node){
	    	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');    
	    	        }    
	    	    }]    
	    	}); 
	    }
	    }
	});  
})

注意:js文件中,是不支持el表达式

7、mvc2.xml中配置子控制器

<?xml version="1.0" encoding="UTF-8"?>
<config>
	
	<action path="/menu" type="com.mwy.web.MenuAction">
		
	</action>
	
</config>

8、index.jsp页面

在js文件中是不支持EL表达式,所以写这行代码

<input type="hidden" id="ctx" value="${pageContext.request.contextPath }">

<%@ 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>Insert title here</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 type="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:100px;">
    
    <!-- 
        缺陷:
        1、样式缺陷
        2、不好做数据的渲染,树形结构的动态显示(重点)
     -->
    <!-- <div class="easyui-panel" style="padding:5px">
		<ul class="easyui-tree">
			<li>
				<span>My Documents</span>
				<ul>
					<li data-options="state:'closed'">
						<span>Photos</span>
						<ul>
							<li>
								<span>Friend</span>
							</li>
							<li>
								<span>Wife</span>
							</li>
							<li>
								<span>Company</span>
							</li>
						</ul>
					</li>
					<li>
						<span>Program Files</span>
						<ul>
							<li>Intel</li>
							<li>Java</li>
							<li>Microsoft Office</li>
							<li>Games</li>
						</ul>
					</li>
					<li>index.html</li>
					<li>about.html</li>
					<li>welcome.html</li>
				</ul>
			</li>
		</ul>
	</div> -->
    
    
    <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>

9、最终展示界面

结束了!!

掰掰 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值