一、转换对应的数据格式(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;}@Overridepublic 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();@Overridepublic Menu getModel() {// TODO Auto-generated method stubreturn 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~~~~

Tree后台实现代码以及运行结果相关推荐

  1. python运行过程中会被编译成二进制_Python代码在运行过程中,会被编译成二进制代码。_学小易找答案...

    [单选题]1. ( )是违反设备安全操作规程的错误做法. [单选题]Thank you for your letter ___________ 24th March. (1.0分) [单选题]超外差接 ...

  2. 一套代码两端运行不靠谱?是时候放弃 C++ 跨 Android、iOS 端开发!

    「Write once,run anywhere!」想必是很多开发者以及企业梦寐以求的愿望,但是在分析跨平台中的种种成本之后,我们不禁发问,这种策略真的靠谱吗? 近日,云存储公司 Dropbox 就此 ...

  3. python写百行代码可运行_56 岁潘石屹学俩月 Python ,写下百行代码

    原标题:56 岁潘石屹学俩月 Python ,写下百行代码 By 超神经 内容导读:跨界王潘石屹在近期迷上了编程,不仅高调宣布学习 Python,拜老师,还隔三差五晒出自己的「编程课作业」,和网友进行 ...

  4. caffe SSD 代码编译运行流程及问题解决

    caffe SSD 代码编译运行流程及问题解决 该文基于以下代码: https://github.com/weiliu89/caffe/tree/ssd down下来后,进入目录 -rw-rw-r-- ...

  5. java tree 树的代码实现

    java tree 树的代码实现 菜单功能等 在开发后台管理系统过程中,菜单功能是必定实现的一个功能,因此针对此功能做个笔记: 树统一接口定义 默认树类的创建 实现树状列表工具类 统一接口定义 pub ...

  6. 大恶人吉日嘎拉之走火入魔闭门造车之.NET疯狂架构经验分享系列之(二)后台服务代码部分

    程序写太长了,大家看着也累,我也写着也很辛苦,接下来,还是写得简短一些,尽量多一些截图,少一些文字吧. 同样是,欢迎指点批评的同学,我虚心学习提高,改改以往的高姿态. 架设软件系统就像大家看饭店厨师炒 ...

  7. 大恶人吉日嘎拉之走火入魔闭门造车之.NET疯狂架构经验分享系列之(二)后台服务代码部分...

    程序写太长了,大家看着也累,我也写着也很辛苦,接下来,还是写得简短一些,尽量多一些截图,少一些文字吧. 同样是,欢迎指点批评的同学,我虚心学习提高,改改以往的高姿态. 架设软件系统就像大家看饭店厨师炒 ...

  8. 操作无法完成后台打印程序无法运行

    同事反映原共享的打印机无法打印.我删除重新添加时系统提示 操作无法完成后台打印程序无法运行.于是我打开服务找到print spooler服务进程设置自动开启后重新添加问题依旧.在网上查到的方法是 病毒 ...

  9. pyinstaller打包生成的exe文件并使用python终止后台的exe程序运行

    pyinstaller打包生成的exe文件并使用python终止后台的exe程序运行 目录 pyinstaller打包生成的exe文件并使用python终止后台的exe程序运行 #pyinstalle ...

最新文章

  1. 在CentOS 6.3 64bit上安装ATS 5.3 LTS版本并测试
  2. 字节跳动技术团队提出「AI渲染」方案,手机端也能实现影视级渲染效果
  3. 英特尔显卡linux管理_英特尔 11 代酷睿大揭秘:这次全是大招
  4. java 求交集 算法_Java计算交集,差集,并集的方法示例
  5. AI:神经网络调参(数据、层数、batch大小,学习率+激活函数+正则化+分类/回归)并进行结果可视化
  6. Fedora GNOME 的常用快捷键
  7. 201671010135 2016--2017java程序设计对java的初步认识和对第一,二章的总结(0)
  8. c++五子棋_Java五子棋实现
  9. HihoCoder - 1879 Rikka with Triangles(极角排序求所有锐角三角形的面积)
  10. .Net Core 商城微服务项目系列(二):使用Ocelot + Consul构建具备服务注册和发现功能的网关...
  11. oracle 24756,关于ORA-24756: transaction does not exist的问题
  12. macos可以升级到指定版本吗_承装承修承试可以跨级升级吗?
  13. 07-02 测试报告-allure
  14. Oracle 常用符号CHR
  15. XPath: A Syntax for Describing Needles and Haystacks(Chapter 3 of XSLT 2nd Edition)
  16. Calendar类和GregorianCalendar类
  17. vscode占用C盘空间迁移到其他盘
  18. 推荐|Java学习资料大全(电子书+视频)
  19. RK3328 中文介绍
  20. python 计算变量的IV值

热门文章

  1. axure 9 如何根据下拉框选值,动态展现内容
  2. 使用SignTool对软件安装包进行数字签名
  3. 网页导航hot图标按钮
  4. web前端高级JavaScript - 彻底掌握基于HTTP网络层的“前端性能优化”
  5. freeswitch使用自签证书,配置WSS
  6. lxml 中没有etree的解决办法
  7. 2012TI杯电子设计大赛
  8. Android TV开发总结(四)通过RecycleView构建一个TV app列表页(仿腾讯视频TV版)
  9. python获得a标签内容
  10. 【乘风伯乐奖】寻找百位乘风者伯乐,邀请新博主入驻即可获奖