Tree后台实现代码以及运行结果

一、转换对应的数据格式(Jackson转json串)

1.1 方式一: 实体类对象转换成json串 ——>json对象

	//如何造出数据 1,new一个JsonObject1对象 2,导入jar包
		JsonObject1 obj1=new JsonObject1("11","学生管理","closed");
		ObjectIdMap om=new ObjectIdMap();
        System.out.println(om.writeValueAsString(obj1));

 1.2 方式二:Map集合转换成json串 ——> json对象

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

运行结果如下(两种方式运行结果一样):

2.1、方式一:获取json数组 实体类对象转换成json ——> json数组

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

 2.2、方式二:map集合转换成json数组  

ObjectMapper om=new ObjectMapper();
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));

 运行结果如下:

结论:在json串的转换结果而言,map等价于对象,list<Map>等价于list<创建的类>

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

需求:把从数据库中拿的值显示到界面菜单上,有层级关系

1、数据库表(t_easyui_menu)

2、项目所需jar包 

 3、项目总结构

 

 方式一:

①第一步创建实体类

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();
		// TODO Auto-generated constructor stub
	}

}

②导入jar包 项目所需jar包

 ③给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>/easyui_03</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>/mvc.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>mvc</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

④建立根目录(conf)给mvc.xml做配置

 

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

⑤写dao方法(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.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.entity.Menu;
 
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 static void main(String[] args) throws Exception {
		MenuDao menuDao=new MenuDao();
		List<Menu> list=menuDao.list(null, null);
		ObjectMapper om =new ObjectMapper();
		System.out.println(om.writeValueAsString(list));
	}
 
}

⑥将测试后的这一串........数据复制  把json串进行格式化 

网址:在线代码格式化

 

 缺陷:

 缺陷:
         1、json串并没有体现出父子层级关系,数据之间都是平级的
          2、json串属性并不是id/text...等easyui要求的属性

 2.方法二

 1.MenuDao(继承BaseDao)

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.util.BaseDao;
import com.zking.util.BuildTree;
import com.zking.util.PageBean;
import com.zking.util.TreeVo;
import com.zking.entity.Menu;
 
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是个键名 随便取名字
			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();
		
		//System.out.println(om.writeValueAsString(list));
		System.out.println(om.writeValueAsString(tree));
	}
 
}

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

 3.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();
	}
 
}

 4.①js文件( js文件中是不支持el表达式)

 $(function(){
$('#stuMenu').tree({    
    url:$("#ctx").val()+'/menu.action?methodName=tree',
    onClick: function(node){
		//alert(node.text);  // 在用户点击的时候提示
    	var exists=$('#stuTabs').tabs('exists',node.text);
    	if(exists){
    		$('#stuTabs').tabs('select',node.text);
    	}else{
    		$('#stuTabs').tabs('add',{    
        	    title:node.text,    
        	    content:'<iframe height="100%" width="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/black/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:200px;">
    
    <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>

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

 6.MenuAction  extends ActionSupport implements ModelDriver<Menu>(子控制器)

package com.zking.web;
 
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
import com.zking.util.TreeVo;
import com.zking.dao.MenuDao;
import com.zking.entity.Menu;
 
public class MenuAction extends ActionSupport implements ModelDriver<Menu> {
	Menu menu=new Menu();
	MenuDao menuDao=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 = menuDao.tree(null, null);
		ResponseUtil.writeJson(resp, tree);
		return null;
	}
}

最终效果:

 

see you~~~~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ElementTree是Python的一个内置模块,用于解析和操作XML文件。它提供了一种简单的方式来遍历XML文档,以及对XML元素进行添加、修改和删除等操作。 要使用ElementTree模块,首先需要先导入它: ```python import xml.etree.ElementTree as ET ``` 在导入模块之后,就可以使用ElementTree来解析XML文件了。在解析XML文件之前,需要先打开XML文件,例如: ```python tree = ET.parse('filename.xml') ``` 实现XML文件的解析之后,就可以对XML文件中的各个元素进行操作了。比如,要获取XML文件中的根元素,可以使用以下代码: ```python root = tree.getroot() ``` 然后,可以使用ElementTree提供的方法来访问和操作XML文件中的元素,例如: ```python # 取得根节点的子节点列表 for child in root: print(child.tag, child.attrib) # 取得所有元素 for elem in tree.iter(): print(elem.tag, elem.attrib) # 获取指定的元素 elem = root.find('elementname') ``` 同样,ElementTree还提供了一些方法来对XML元素进行添加、修改和删除等操作。例如,要向XML文件中添加一个新的元素,可以使用以下代码: ```python new_elem = ET.SubElement(root, 'new_element') new_elem.text = 'hello' ``` 这样,就成功地在XML文件中添加了一个名为“new_element”的新元素,并为它设置了文本值。 综合来说,ElementTree提供了一种简单而强大的方式来处理XML文件。使用ElementTree,你可以轻松地读取、编辑和创建XML文件,使得XML文件的处理变得容易而简单。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值