基于EasyUI Treegrid的权限管理资源列表

时间:2021-10-16 23:24:04

1. 前言

最近在开发系统权限管理相关的功能,主要包含用户管理,资源管理,角色管理,组类别管理等小的模块。之前的Web开发中也用过jQueryEasyUI插件,感觉这款插件简单易用,上手很快。以前用到的主要是Datagrid组件,这次为了区分资源的父子关系,打造更好的用户体验,遂探索一下Treegrid组件。

2.jQueryEasyUI简介

jQuery EasyUI是一组基于jQuery的UI插件集合体,而jQuery EasyUI的目标就是帮助web开发者更轻松的打造出功能丰富并且美观的UI界面。开发者不需要编写复杂的javascript,也不需要对css样式有深入的了解,开发者需要了解的只有一些简单的html标签。

EasyUI Treegrid树形网格:扩展自 $.fn.datagrid.defaults。通过 $.fn.treegrid.defaults 重写默认的 defaults。树形网格(treegrid)用于以网格形式显示分层数据。它是基于数据网格(datagrid)的,并结合了树视图(treeview)和可编辑网格。树形网格(treegrid)允许您创建可定制的、可异步展开的行,并以多列形式显示分层数据。

jQuery EasyUI官网:http://www.jeasyui.com/

jQuery EasyUI中文网:Treegrid:http://www.jeasyui.net/plugins/186.html

3.基于EasyUI Treegrid的权限管理资源列表

⑴ 引入EasyUI相关的js和css文件:

<script type="text/javascript" src="/assets/scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/assets/scripts/jquery-easyui-1.4.5/jquery.min.js"></script>
<script type="text/javascript" src="/assets/scripts/jquery-easyui-1.4.5/jquery.easyui.min.js"></script>
<link rel="stylesheet" type="text/css" href="/assets/scripts/jquery-easyui-1.4.5/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="/assets/scripts/jquery-easyui-1.4.5/themes/icon.css">

⑵ 在HTML标签中创建树形网格(treegrid):

<table id="tgTab" title="查询结果" class="easyui-treegrid" style="width:1080px;height:450px">
<thead>
<tr>
<th data-options="field:'name',width:160">资源名称</th>
<th data-options="field:'description',width:100">资源描述</th>
<th data-options="field:'code',width:100, align:'center' ">标识码</th>
<th data-options="field:'type',width:50, align:'center' ">类型</th>
<th data-options="field:'status',width:40, align:'center' ">状态</th>
<th data-options="field:'gmtCreate',width:80,align:'center' ">创建时间</th>
<th data-options="field:'gmtModified',width:80, align:'center'">最后修改时间</th>
<th data-options="field:'id',width:60,formatter:rowFormatter, align:'center' ">操作</th>
</tr>
</thead>
</table>

⑶ Js初始化Treegrid资源列表:

(function($){
function pagerFilter(data){
if ($.isArray(data)){
data = {
total: data.length,
rows: data
}
}
var dg = $(this);
var state = dg.data('treegrid');
var opts = dg.treegrid('options');
var pager = dg.treegrid('getPager');
pager.pagination({
onSelectPage:function(pageNum, pageSize){
opts.pageNumber = pageNum;
opts.pageSize = pageSize;
pager.pagination('refresh',{
pageNumber: pageNum,
pageSize: pageSize,
beforePageText: '第', //页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录'
});
dg.treegrid('loadData',state.originalRows);
},
beforePageText: '第', //页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录'
});
if (!state.originalRows){
state.originalRows = data.rows;
}
var topRows = [];
var childRows = [];
$.map(state.originalRows, function(row){
row._parentId ? childRows.push(row) : topRows.push(row);
});
data.total = topRows.length;
var start = (opts.pageNumber-1)*parseInt(opts.pageSize);
var end = start + parseInt(opts.pageSize);
data.rows = $.extend(true,[],topRows.slice(start, end).concat(childRows));
return data;
} var appendMethod = $.fn.treegrid.methods.append;
var loadDataMethod = $.fn.treegrid.methods.loadData;
$.extend($.fn.treegrid.methods, {
clientPaging: function(jq){
return jq.each(function(){
var state = $(this).data('treegrid');
var opts = state.options;
opts.loadFilter = pagerFilter;
var onBeforeLoad = opts.onBeforeLoad;
opts.onBeforeLoad = function(row,param){
state.originalRows = null;
onBeforeLoad.call(this, row, param);
};
$(this).treegrid('loadData', state.data);
$(this).treegrid('reload');
});
},
loadData: function(jq, data){
jq.each(function(){
$(this).data('treegrid').originalRows = null;
});
return loadDataMethod.call($.fn.treegrid.methods, jq, data);
},
append: function(jq, param){
return jq.each(function(){
var state = $(this).data('treegrid');
if (state.options.loadFilter == pagerFilter){
$.map(param.data, function(row){
row._parentId = row._parentId || param.parent;
state.originalRows.push(row);
});
$(this).treegrid('loadData', state.originalRows);
} else {
appendMethod.call($.fn.treegrid.methods, jq, param);
}
})
}
});
})(jQuery); $(function(){
$('#tgTab').treegrid({
iconCls: 'icon-ok',
rownumbers: true,
animate: true,
collapsible: true,
fitColumns: true,
url: '../api/initResourcesList?type=-1',
method: 'get',
idField: 'id',
treeField: 'name',
pagination: true,
pageSize: 80,
pageList: [80,120,160]
}).treegrid('clientPaging');
}); function rowFormatter(value, row, index){
//value为该条数据的field字段的值,row为该行(显示在页面)数据的所有信息,index当前行,单引号里面必须双引号,双引号里面必须单引号,里面再有就需转义
return '<img id="update" src="/assets/images/layout/update.png" onclick="updateRes('+value+')"/>&nbsp;&nbsp;' +
'&nbsp;&nbsp;<img id="delete" src="/assets/images/layout/delete.png" onclick="deleteRes('+value+')"/>';
}

⑷ Java后台生成资源列表JSON数据:

/**
* 将资源封装成资源树
* @param list
* @param parentId
*/
@SuppressWarnings("deprecation")
private List<Map<String,Object>> createTreeGridTree(List<UsersResource> list) {
//存放转换后的资源树
List<Map<String,Object>> treeGridList =new ArrayList<Map<String,Object>>(); for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = null;
UsersResource res = list.get(i);
if (res.getParentId().equals(0)) {
map = new HashMap<String, Object>();
map.put("id", res.getId());
map.put("name", res.getName());
map.put("description", res.getDescription());
map.put("code", res.getCode());
if (res.getType() == 0) {
map.put("type", "URL资源");
} else if (res.getType() == 1) {
map.put("type", "组件资源");
} else {
map.put("type", "虚拟根资源");
}
if (res.getStatus() == 0) {
map.put("status", "隐藏");
} else {
map.put("status", "显示");
}
map.put("gmtCreate", res.getGmtCreate().toLocaleString());
map.put("gmtModified", res.getGmtModified().toLocaleString());
map.put("children", createTreeGridChildren(list, res.getId()));
}
if (map != null) {
treeGridList.add(map);
}
}
return treeGridList;
} /**
* 递归设置资源树
* @param list
* @param parentId
* @return childList
*/
@SuppressWarnings("deprecation")
private List<Map<String, Object>> createTreeGridChildren(List<UsersResource> list, int parentId) {
List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
for (int j = 0; j < list.size(); j++) {
Map<String, Object> map = null;
UsersResource treeChild = list.get(j);
if (treeChild.getParentId().equals(parentId)) {
map = new HashMap<String, Object>();
map.put("id", treeChild.getId());
map.put("name", treeChild.getName());
map.put("description", treeChild.getDescription());
map.put("code", treeChild.getCode());
if (treeChild.getType() == 0) {
map.put("type", "URL资源");
} else if (treeChild.getType() == 1) {
map.put("type", "组件资源");
} else {
map.put("type", "虚拟根资源");
}
if (treeChild.getStatus() == 0) {
map.put("status", "隐藏");
} else {
map.put("status", "显示");
}
map.put("gmtCreate", treeChild.getGmtCreate().toLocaleString());
map.put("gmtModified", treeChild.getGmtModified().toLocaleString());
map.put("children", createTreeGridChildren(list, treeChild.getId()));
} if (map != null) {
childList.add(map);
}
}
return childList;
} @GET
@Path("initResourcesList")
@Override
public Object initResourcesList(String page, String rows, String name,
String code, int type) {
System.out.println("资源传参:page:"+ page +",rows:"+ rows +
",name:"+ name +",code:"+ code + ",type:"+ type); UsersResource usersRes = new UsersResource();
usersRes.setName(name);
usersRes.setCode(code);
usersRes.setType(type);
int recordNum = 0; // 总记录数
recordNum = usersResourceService.getUsersResourceTotalNumBySQL(usersRes);
//System.out.println("资源总条数:" + recordNum); // *******分页******************
int pageSize = 80;
pageSize = Integer.parseInt(rows);
int curPageNo = 1;
curPageNo = Integer.parseInt(page); // 当前页号
int startIndex = 0; // 开始索引
if (recordNum > 0) {
if (curPageNo == 1) {
startIndex = 0; // 开始索引
} else {
startIndex = curPageNo * pageSize - pageSize; // 开始索引
}
}
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("startIndex", startIndex);
paramMap.put("pageSize", pageSize);
paramMap.put("name", name);
paramMap.put("code", code);
paramMap.put("type", type); List<UsersResource> resourceList = new ArrayList<UsersResource>();
resourceList = usersResourceService.searchUsersResourceBySQL(paramMap); Map<String, Object> result = new HashMap<String, Object>(2);
JSONArray jsonArray = new JSONArray(); List<Map<String,Object>> treeGridList =new ArrayList<Map<String,Object>>();
//调用方法实现树
treeGridList = createTreeGridTree(resourceList);
jsonArray = JSONArray.fromObject(treeGridList); result.put("total", recordNum);
result.put("rows", jsonArray);
//System.out.println("json:" + JSONObject.fromObject(result).toString());
return JSONObject.fromObject(result);
}

Model类:UsersResource

package com.ouc.mkhl.platform.authority.model;

import java.io.Serializable;
import java.util.Date; //RBAC权限管理用户资源信息
public class UsersResource implements Serializable { private static final long serialVersionUID = 10002121L; private Integer id; //用户资源Id private Integer authId; //权限中心资源Id private String name; //资源名称 private String description; //资源描述 private String url; //链接地址 private Integer type; //资源类型:0-URL资源,1-组件资源 private Integer status; //状态:0-隐藏,1-展示 private String code; //标识码 private String configuration; //配置项 private String moduleName; //模块名称 private Date gmtCreate; //创建时间 private Date gmtModified; //最后修改时间 private String createBy; //创建人 private String lastModifedBy; //最后修改人 private Integer orderIndex; //排序号 private Integer parentId; //父资源 public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public Integer getAuthId() {
return authId;
} public void setAuthId(Integer authId) {
this.authId = authId;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description == null ? null : description.trim();
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url == null ? null : url.trim();
} public Integer getType() {
return type;
} public void setType(Integer type) {
this.type = type;
} public Integer getStatus() {
return status;
} public void setStatus(Integer status) {
this.status = status;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code == null ? null : code.trim();
} public String getConfiguration() {
return configuration;
} public void setConfiguration(String configuration) {
this.configuration = configuration == null ? null : configuration
.trim();
} public String getModuleName() {
return moduleName;
} public void setModuleName(String moduleName) {
this.moduleName = moduleName == null ? null : moduleName.trim();
} public Date getGmtCreate() {
return gmtCreate;
} public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
} public Date getGmtModified() {
return gmtModified;
} public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
} public String getCreateBy() {
return createBy;
} public void setCreateBy(String createBy) {
this.createBy = createBy == null ? null : createBy.trim();
} public String getLastModifedBy() {
return lastModifedBy;
} public void setLastModifedBy(String lastModifedBy) {
this.lastModifedBy = lastModifedBy == null ? null : lastModifedBy
.trim();
} public Integer getOrderIndex() {
return orderIndex;
} public void setOrderIndex(Integer orderIndex) {
this.orderIndex = orderIndex;
} public Integer getParentId() {
return parentId;
} public void setParentId(Integer parentId) {
this.parentId = parentId;
}
}

4.资源列表最终效果

基于EasyUI Treegrid的权限管理资源列表

最终效果丑了点,需要请美工美化一下,还有分页的地方有个Bug需要改一改。分页Bug如下图:

基于EasyUI Treegrid的权限管理资源列表

Treegrid扩展自Datagrid,用过Datagrid的这个学起来也不是很难。