一、转换对应的数据格式(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~~~~