1.添加fastjson依赖,用于json转换
pom.xml
<!--阿里json转换-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
2.Permission实体类
Permission类
@TableName("t_permission")
public class Permission {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String permissionKey;
@TableField(value = "permissionName")
private String title;
/**
* 父节点ID
*/
private Integer pId;
/**
* 节点集合
*/
@TableField(exist = false)
private List<Permission> children = new ArrayList<>();
/**
* 是否被选中
*/
@TableField(exist = false)
private Boolean checked = false;
/**
* 递归添加节点
* @param node
*/
public void addNode(Permission node) {
// 顶级节点
if (node.pId == 0) {
this.children.add(node);
}
// 同级节点
else if (node.pId.equals(this.id)) {
this.children.add(node);
}
// 搜查对应节点
else {
for (Permission tmpNode : children) {
tmpNode.addNode(node);
}
}
}
// SET/GET省略
}
3.PermissionMapper及映射文件
PermissionMapper
@Mapper
@Repository
public interface PermissionMapper extends BaseMapper<Permission> {
/**
* 根据角色ID获取所有权限
* @param roleId
* @return
*/
List<Permission> getPermissionListByRoleId(@Param("roleId") Integer roleId);
/**
* 根据角色确认权限
* @param roleId
* @param permissionId
* @return
*/
Integer getRolePermissionCount(@Param("roleId") Integer roleId, @Param("permissionId") Integer permissionId);
}
PermissionMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cx.eduproj.mapper.PermissionMapper">
<select id="getPermissionListByRoleId" resultType="Permission">
SELECT
b.id,
b.permissionKey,
b.permissionName
FROM
t_role_permission a
LEFT JOIN t_permission b ON a.permissionId = b.id
WHERE a.roleId = #{roleId}
</select>
<select id="getRolePermissionCount" resultType="int">
SELECT
COUNT(*)
FROM
t_role_permission
WHERE roleId = #{roleId} AND permissionId = #{permissionId}
</select>
</mapper>
4.IPermissionService及实现类
IPermissionService
public interface IPermissionService {
/**
* 获取数据库中权限树
* @param roleId
* @return
*/
String getPermissionTreeString(Integer roleId);
}
PermissionServiceImpl
@Service
public class PermissionServiceImpl implements IPermissionService {
@Autowired
PermissionMapper permissionMapper;
@Override
public String getPermissionTreeString(Integer roleId) {
Subject subject = SecurityUtils.getSubject();
// 获取所有权限集合
List<Permission> permissionList = permissionMapper.selectList(null);
// 初始化权限树对象
Permission permissionTree = new Permission();
// 权限节点
Permission node;
// 添加节点
for (Permission permission : permissionList) {
node = new Permission(permission.getId(), permission.getPermissionKey(), permission.getTitle(), permission.getpId());
// 根据角色确认是否存在该权限
Integer result = permissionMapper.getRolePermissionCount(roleId, permission.getId());
if (result > 0) {
node.setChecked(true);
}
// 将节点添加至树中
permissionTree.addNode(node);
}
return JSONObject.toJSONString(permissionTree);
}
}
5.编写PermissionController
PermissionController
@RestController
@RequestMapping("/permission")
public class PermissionController {
private static Logger logger= LoggerFactory.getLogger(PermissionController.class);
@Autowired
IPermissionService permissionService;
/**
* 跳转树形菜单页面
*/
@RequestMapping("/toTree")
public ModelAndView toTree(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("tree");
return modelAndView;
}
/**
* 获取数据库权限树
* @return
*/
@RequestMapping("/tree")
public String treeString(@Param("roleId") Integer roleId) {
return permissionService.getPermissionTreeString(roleId);
}
}
6.编写tree页面
tree.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>树组件</title>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" th:href="@{/css/font.css}">
<link rel="stylesheet" th:href="@{/css/xadmin.css}">
<script type="text/javascript"
src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script th:src="@{/lib/layui/layui.js}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/js/xadmin.js}"></script>
</head>
<body>
<!--选择框-->
<form class="layui-form" action="">
<div class="layui-form-item">
<label class="layui-form-label">请选择角色</label>
<div class="layui-input-block">
<select lay-filter="selectForm" id="roleId" name="roleId" lay-verify="required">
<option value="3">管理员</option>
<option value="1">学生</option>
<option value="2">老师</option>
</select>
</div>
</div>
</form>
<!--树形表格-->
<div id="tree"></div>
<script>
layui.use(['tree', 'form'], function () {
// 初始化表单
refreshTree();
// 监听select
var form = layui.form;
form.on('select(selectForm)',function (data) {
console.log(data.elem);
console.log(data.value);
console.log(data.othis);
refreshTree();
});
// 初始化加载
function refreshTree() {
var roleId = $("#roleId").val();
if (roleId == "" || roleId == undefined || roleId == null) {
// 默认显示管理员
roleId = 3;
}
// 获取树形表格数据
var jsonData;
$.ajax({
url: "tree",
data:{roleId: roleId},
dataType: "json",
async: false,
success: function (data) {
jsonData = data.children;
}
});
var tree = layui.tree;
//渲染
var inst1 = tree.render({
elem: '#tree' //绑定元素
, data: jsonData
, showCheckbox: true // 是否显示复选框
, oncheck: function (obj) {
console.log(obj.data); //得到当前点击的节点数据
console.log(obj.checked); //得到当前节点的展开状态:open、close、normal
console.log(obj.elem); //得到当前节点元素
}
});
}
})
</script>
</body>
</html>
7.效果展示
附:对应数据库
t_role表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_role
-- ----------------------------
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`roleKey` varchar(255) DEFAULT NULL COMMENT '角色键',
`roleName` varchar(255) DEFAULT NULL COMMENT '角色名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_role
-- ----------------------------
INSERT INTO `t_role` VALUES ('1', 'student', '学生');
INSERT INTO `t_role` VALUES ('2', 'teacher', '老师');
INSERT INTO `t_role` VALUES ('3', 'admin', '管理员');
t_role_permission表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `t_role_permission`;
CREATE TABLE `t_role_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`roleId` int(11) DEFAULT NULL,
`permissionId` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of t_role_permission
-- ----------------------------
INSERT INTO `t_role_permission` VALUES ('5', '2', '2');
INSERT INTO `t_role_permission` VALUES ('6', '2', '3');
INSERT INTO `t_role_permission` VALUES ('7', '2', '7');
INSERT INTO `t_role_permission` VALUES ('8', '3', '1');
INSERT INTO `t_role_permission` VALUES ('9', '3', '2');
INSERT INTO `t_role_permission` VALUES ('11', '3', '5');
INSERT INTO `t_role_permission` VALUES ('14', '3', '3');
INSERT INTO `t_role_permission` VALUES ('16', '3', '9');
INSERT INTO `t_role_permission` VALUES ('17', '3', '8');
INSERT INTO `t_role_permission` VALUES ('18', '1', '8');
INSERT INTO `t_role_permission` VALUES ('19', '3', '12');
INSERT INTO `t_role_permission` VALUES ('26', '3', '13');
INSERT INTO `t_role_permission` VALUES ('28', '3', '4');
t_permission表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_permission
-- ----------------------------
DROP TABLE IF EXISTS `t_permission`;
CREATE TABLE `t_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`permissionKey` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`permissionName` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`pId` int(11) DEFAULT NULL COMMENT '父节点ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of t_permission
-- ----------------------------
INSERT INTO `t_permission` VALUES ('1', 'user', '用户管理', '0');
INSERT INTO `t_permission` VALUES ('2', 'course', '课程管理', '0');
INSERT INTO `t_permission` VALUES ('3', 'homework', '作业管理', '0');
INSERT INTO `t_permission` VALUES ('4', 'user_add', '用户管理-添加用户', '1');
INSERT INTO `t_permission` VALUES ('5', 'user_list', '用户管理-用户列表', '1');
INSERT INTO `t_permission` VALUES ('6', 'mycourse', '课程管理-我的课程', '2');
INSERT INTO `t_permission` VALUES ('7', 'course_teacher', '课程管理-讲师', '2');
INSERT INTO `t_permission` VALUES ('8', 'myhomework', '作业管理-我的作业', '3');
INSERT INTO `t_permission` VALUES ('9', 'home_add', '作业管理-作业发布', '3');
INSERT INTO `t_permission` VALUES ('11', 'checkhomework', '课程管理-讲师-作业讲评', '7');
INSERT INTO `t_permission` VALUES ('12', 'user_edit', '用户管理-编辑用户', '1');
INSERT INTO `t_permission` VALUES ('13', 'user_deleteBatch', '用户管理-批量删除', '1');
INSERT INTO `t_permission` VALUES ('14', 'home_delete', '作业管理-作业删除', '3');