前言:在上一篇文章中我们通过EasyUI框架的树(tree)、选项卡(tabs)两个组件;做出页面中通过点击菜单,显示菜单对应的页面,但是数据来源并非是活数据,而是写死在JSON文件中的数据,在项目开发中数据都是来源于数据库所有写死在JSON文件中就存在着一定的弊端。现在我们通过读取数据库中的数据来实现前端效果。
EasyUI需求的JSON数据格式
1.实体类对象转换JSON对象
首先将数据库读取出来的数据转换成JSON数据。引入jar包
1.1创建实体类
package com.wyy.entity;
public class menu {
private String serialNo;//序列号
private String menuid; //节点id
private String menuname;//节点名字
private String menuURL;//当前节点对应的页面路径
private String parentid;//父节点ID
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 + "]";
}
}
1.2读取数据将数据转换成json
public static void main(String[] args) throws Exception {
menudao d=new menudao();
//读取数据库所有数据
List<menu> list = d.list(null, null);
//将读取出来的数据转换成JSON数据
ObjectMapper o=new ObjectMapper();
String ss = o.writeValueAsString(list);
//输出
System.out.println(ss);
}
成功读取所有数据
[{"serialNo":"059CB9B033C247A1AD4B3F0E78C0ED55","menuid":"004003003","menuname":"用户权限管理","menuURL":"jsp/userManage.jsp","parentid":"004003"},{"serialNo":"0AAADCF1F3884271A5C42EE845F47317","menuid":"003001002","menuname":"升学学费","menuURL":"jsp/finance/higherGrade","parentid":"003001"}
在后台输出的json对象中
- json对象没有体现出父子层级关系,数据是平级关系
- json串属性并不是easyui要求的属性
2创建符合EasyUI树形组件的属性对象
2.1参考EasyUI的API 建立符合EasyUI树形组件需求的属性对象
package com.wyy.entity;
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();
}
}
2.2将读取出来的对象属性变成符合easyui属性需求的对象属性
/**
* 获取所有数据
* @param m
* @param p
* @return
* @throws Exception
*/
public List<TreeVo<menu>> tree(menu m,PageBean p) throws Exception{
//获取所有数据
List<menu> list = this.list(m, p);
//List<menu> --->> List<Tree<menu>>
List<TreeVo<menu>> tv=new ArrayList<TreeVo<menu>>();
for (menu me : list) {
//实例化对象TreeVo<menu>,将值赋值给
TreeVo<menu> treevo=new TreeVo<menu>();
treevo.setId(me.getMenuid());
treevo.setText(me.getMenuname());
treevo.setParentId(me.getParentid());
Map<String, Object> map=new HashMap<>();
map.put("s", me);
treevo.setAttributes(map);
tv.add(treevo);
}
return tv;
}
public static void main(String[] args) throws Exception {
menudao d=new menudao();
//读取数据库所有数据
List<TreeVo<menu>> list = d.tree(null, null);
//将读取出来的数据转换成JSON数据
ObjectMapper o=new ObjectMapper();
String ss = o.writeValueAsString(list);
System.out.println(ss);
}
[{"id":"004003003","text":"用户权限管理","state":null,"checked":false,"attributes":{"s":{"serialNo":"059CB9B033C247A1AD4B3F0E78C0ED55","menuid":"004003003","menuname":"用户权限管理","menuURL":"jsp/userManage.jsp","parentid":"004003"}},"children":[],"parentId":"004003","hasParent":false,"hasChildren":false},{"id":"003001002","text":"升学学费","state":null,"checked":false,"attributes":{"s":{"serialNo":"0AAADCF1F3884271A5C42EE845F47317","menuid":"003001002","menuname":"升学学费","menuURL":"jsp/finance/higherGrade","parentid":"003001"}},"children":[],"parentId":"003001","hasParent":false,"hasChildren":false},{"id":"003003","text":"住宿费","state":null,"checked":false,"attributes":{"s":费","menuURL":null,"parentid":"003"}},"children":
对比两次输出结果可以看到属性名已经更改成了EasyUI树(tree)规范的属性;但是数据中依旧没有父子层级关系
2.3让List<Tree<menu>> 中的数据有父子层级关系
遍历List<Tree<menu>>集合,建立顶级节点,当外层循环节点id等于内层循环的父id,那么
就意味着内层循环中当前循环的节点是外层循环节点的子节点,就可以把内层循环的节点放到
外层循环节点的children属性中。
package com.zking.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.wyy.entity.TreeVo;
public class BuildTree {
/**
* 默认-1为顶级节点
* @param nodes
* @param <T> easyui
* @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();//获取当前父节点id
if (pid == null || "-1".equals(pid)) {
topNodes.add(children);
continue;
}
for (TreeVo<T> parent : nodes) {
String id = parent.getId();//子节点id
if (id != null && id.equals(pid)) {//子节点ID等于父id
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;
}
}
输出、JSON转换封装类
package com.wyy.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();
write(response, om.writeValueAsString(o));
}
}
调用对应方法处理结果数据 ,ajax请求没有返回值,输出即可
public String tree(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//获取EasyUI可以识别的对象集合
List<TreeVo<menu>> tree = d.tree(null, null);
//层级关系处理
List<TreeVo<menu>> buildList = BuildTree.buildList(tree, "-1");
//输出
ResponseUtil.writeJSON(resp, buildList);
return null;
}
在界面定义隐藏的绝对路径
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<link rel="stylesheet" type="text/css"
href="easyUI/jquery-easyui-1.5.1/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
href="easyUI/jquery-easyui-1.5.1/themes/icon.css">
<script type="text/javascript"
src="easyUI/jquery-easyui-1.5.1/jquery.min.js"></script>
<script type="text/javascript"
src="easyUI/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<!-- js文件 -->
<script type="text/javascript" src="easyUI/js/index.js"></script>
<body class="easyui-layout">
<!-- 定义绝对路径 -->
<input type="hidden" value="${pageContext.request.contextPath}" id="hh">
<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',title:'东部',split:false"
style="width: 100px;"></div>
<div data-options="region:'west',title:'西部',split:true"
style="width: 100px;">
<ul id="stu"></ul>
</div>
<div data-options="region:'center',title:'中部'"
style="padding: 5px; background: # eee;">
<div id="tt" class="easyui-tabs" style="width: 100%; height: 100%">
</div>
</div>
</body>
</html>
js文件中,更改数据源
$(function() {
$('#stu').tree({
url: $("#hh").val()+'/menu.action?methodName=tree',
onClick: function(nodd) {
var exists = $('#tt').tabs('exists', nodd.text);
if (exists) {
$('#tt').tabs('select', nodd.text);
} else {
$('#tt').tabs('add', {
title: nodd.text,
content: '<iframe src="' + nodd.attributes.url + '" style="width: 100%; height: 100%"></iframe>',
closable: true,
tools: [{
iconCls: 'icon-mini-refresh',
handler: function() {
alert('refresh');
}
}]
});
}
}
});
})
数据库数据源
最终效果