SpringMVC+ZTree实现树形菜单权限配置的方法

时间:2022-12-02 13:07:44

计划在开源项目里加入权限配置的功能,打算加入ztree实现树形结构。

team的github开源项目链接:https://github.com/u014427391/jeeplatform 欢迎star(收藏)

ztree 是一个依靠 jquery 实现的多功能 “树插件”。优异的性能、灵活的配置、多种功能的组合是 ztree 最大优点。

ztree下载链接:http://www.treejs.cn/v3/main.php#_ztreeinfo

SpringMVC+ZTree实现树形菜单权限配置的方法

角色信息实体类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package org.muses.jeeplatform.core.entity.admin;
import javax.persistence.*;
import java.io.serializable;
import java.util.hashset;
import java.util.set;
/**
 * @description 角色信息实体类
 * @author nicky
 * @date 2017年3月16日
 */
@table(name="sys_role")
@entity
public class role implements serializable{
  /** 角色id**/
  private int roleid;
  /** 角色描述**/
  private string roledesc;
  /** 角色名称**/
  private string rolename;
  /** 角色标志**/
  private string role;
  private set<permission> permissions = new hashset<permission>();
 
  @id
  @generatedvalue(strategy=generationtype.identity)
  public int getroleid() {
    return roleid;
  }
 
  public void setroleid(int roleid) {
    this.roleid = roleid;
  }
 
  @column(length=100)
  public string getroledesc() {
    return roledesc;
  }
 
  public void setroledesc(string roledesc) {
    this.roledesc = roledesc;
  }
 
  @column(length=100)
  public string getrolename() {
    return rolename;
  }
 
  public void setrolename(string rolename) {
    this.rolename = rolename;
  }
 
  @column(length=100)
  public string getrole() {
    return role;
  }
 
  public void setrole(string role) {
    this.role = role;
  }
  //修改cascade策略为级联关系
  @onetomany(targetentity=permission.class,cascade=cascadetype.merge,fetch=fetchtype.eager)
  @jointable(name="sys_role_permission", joincolumns=@joincolumn(name="roleid",referencedcolumnname="roleid"), inversejoincolumns=@joincolumn(name="permissionid",referencedcolumnname="id",unique=true))
  public set<permission> getpermissions() {
    return permissions;
  }
 
  public void setpermissions(set<permission> permissions) {
    this.permissions = permissions;
  }
 
  @override
  public boolean equals(object obj) {
    if (obj instanceof role) {
      role role = (role) obj;
      return this.roleid==(role.getroleid())
          && this.rolename.equals(role.getrolename())
          && this.roledesc.equals(role.getroledesc())
          && this.role.equals(role.getrole());
    }
    return super.equals(obj);
  }
}

权限信息实体类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package org.muses.jeeplatform.core.entity.admin;
import java.io.serializable;
import java.util.hashset;
import java.util.set;
import javax.persistence.cascadetype;
import javax.persistence.column;
import javax.persistence.entity;
import javax.persistence.fetchtype;
import javax.persistence.generatedvalue;
import javax.persistence.generationtype;
import javax.persistence.id;
import javax.persistence.joincolumn;
import javax.persistence.jointable;
import javax.persistence.manytomany;
import javax.persistence.onetoone;
import javax.persistence.table;
/**
 * @description 权限操作的vo类
 * @author nicky
 * @date 2017年3月6日
 */
@table(name="sys_permission")
@entity
public class permission implements serializable {
  private int id;
  private string pdesc;
  private string name;
  private static final long serialversionuid = 1l;
  private menu menu;
  private set<operation> operations = new hashset<operation>();
  public permission() {
    super();
  }
 
  @generatedvalue(strategy = generationtype.identity)
  @id
  public int getid() {
    return this.id;
  }
 
  public void setid(int id) {
    this.id = id;
  }
 
  @column(length=100)
  public string getpdesc() {
    return this.pdesc;
  }
 
  public void setpdesc(string pdesc) {
    this.pdesc = pdesc;
  }
 
  @column(length=100)
  public string getname() {
    return this.name;
  }
 
  public void setname(string name) {
    this.name = name;
  }
 
  @onetoone(targetentity=menu.class,cascade=cascadetype.refresh,fetch=fetchtype.eager)
  @joincolumn(name="menuid",referencedcolumnname="menuid")
  public menu getmenu() {
    return menu;
  }
 
  public void setmenu(menu menu) {
    this.menu = menu;
  }
 
  @manytomany(targetentity=operation.class,cascade=cascadetype.merge,fetch=fetchtype.eager)
  @jointable(name="sys_permission_operation",joincolumns=@joincolumn(name="permissionid",referencedcolumnname="id"),inversejoincolumns=@joincolumn(name="operationid",referencedcolumnname="id"))
  public set<operation> getoperations() {
    return operations;
  }
 
  public void setoperations(set<operation> operations) {
    this.operations = operations;
  }
}

实现菜单信息实体类,用jpa来实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package org.muses.jeeplatform.core.entity.admin;
import javax.persistence.*;
import java.io.serializable;
import java.util.list;
/**
 * @description 菜单信息实体
 * @author nicky
 * @date 2017年3月17日
 */
@table(name="sys_menu")
@entity
public class menu implements serializable {
  /** 菜单id**/
  private int menuid; 
  /** 上级id**/
  private int parentid; 
  /** 菜单名称**/
  private string menuname; 
  /** 菜单图标**/
  private string menuicon; 
  /** 菜单url**/
  private string menuurl; 
  /** 菜单类型**/
  private string menutype;
  /** 菜单排序**/
  private string menuorder;
  /**菜单状态**/
  private string menustatus;
  private list<menu> submenu;
  private string target;
  private boolean hassubmenu = false;
  public menu() {
    super();
  
  
  @id
  @generatedvalue(strategy=generationtype.identity)
  public int getmenuid() {
    return this.menuid;
  }
 
  public void setmenuid(int menuid) {
    this.menuid = menuid;
  }
 
  @column(length=100)
  public int getparentid() {
    return parentid;
  }
 
  public void setparentid(int parentid) {
    this.parentid = parentid;
  }
 
  @column(length=100)
  public string getmenuname() {
    return this.menuname;
  }
 
  public void setmenuname(string menuname) {
    this.menuname = menuname;
  
  
  @column(length=30)
  public string getmenuicon() {
    return this.menuicon;
  }
 
  public void setmenuicon(string menuicon) {
    this.menuicon = menuicon;
  
  
  @column(length=100)
  public string getmenuurl() {
    return this.menuurl;
  }
 
  public void setmenuurl(string menuurl) {
    this.menuurl = menuurl;
  
  
  @column(length=100)
  public string getmenutype() {
    return this.menutype;
  }
 
  public void setmenutype(string menutype) {
    this.menutype = menutype;
  }
 
  @column(length=10)
  public string getmenuorder() {
    return menuorder;
  }
 
  public void setmenuorder(string menuorder) {
    this.menuorder = menuorder;
  }
 
  @column(length=10)
  public string getmenustatus(){
    return menustatus;
  }
 
  public void setmenustatus(string menustatus){
    this.menustatus = menustatus;
  }
 
  @transient
  public list<menu> getsubmenu() {
    return submenu;
  }
 
  public void setsubmenu(list<menu> submenu) {
    this.submenu = submenu;
  }
 
  public void settarget(string target){
    this.target = target;
  }
 
  @transient
  public string gettarget(){
    return target;
  }
 
  public void sethassubmenu(boolean hassubmenu){
    this.hassubmenu = hassubmenu;
  }
 
  @transient
  public boolean gethassubmenu(){
    return hassubmenu;
  }
 
}

实现jparepository接口

?
1
2
3
4
5
6
7
8
9
package org.muses.jeeplatform.core.dao.repository.admin;
import org.muses.jeeplatform.core.entity.admin.role;
import org.springframework.data.jpa.repository.jparepository;
/**
 * created by nicky on 2017/12/2.
 */
public interface rolerepository extends jparepository<role,integer> {
 
}

实现jparepository接口

?
1
2
3
4
5
6
7
8
9
package org.muses.jeeplatform.core.dao.repository.admin;
import org.muses.jeeplatform.core.entity.admin.menu;
import org.springframework.data.jpa.repository.jparepository;
/**
 * created by nicky on 2017/6/17.
 */
public interface menutreerepository extends jparepository<menu,integer>{
 
}

角色service类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package org.muses.jeeplatform.service;
import com.google.common.collect.lists;
import org.muses.jeeplatform.core.dao.repository.admin.rolepagerepository;
import org.muses.jeeplatform.core.entity.admin.role;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.domain.page;
import org.springframework.data.domain.pagerequest;
import org.springframework.data.domain.sort;
import org.springframework.stereotype.service;
import java.util.list;
/**
 * created by nicky on 2017/7/30.
 */
@service
public class rolepageservice {
  @autowired
  rolepagerepository rolerepository;
 
  /**
   * 构建pagerequest对象
   * @param num
   * @param size
   * @param asc
   * @param string
   * @return
   */
  private pagerequest buildpagerequest(int num, int size, sort.direction asc,
                     string string) {
    return new pagerequest(num-1, size,null,string);
  }
 
  /**
   * 获取所有的菜单信息并分页显示
   * @param pageno
   *     当前页面数
   * @param pagesize
   *     每一页面的页数
   * @return
   */
  public page<role> findall(int pageno, int pagesize, sort.direction dir, string str){
    pagerequest pagerequest = buildpagerequest(pageno, pagesize, dir, str);
    page<role> roles = rolerepository.findall(pagerequest);
    return roles;
  }
 
  public list<role> findallrole(){
    iterable<role> roles = rolerepository.findall();
    list<role> mylist = lists.newarraylist(roles);
    return mylist;
  }
 
  /**
   * 根据角色id查找角色信息
   * @param roleid
   * @return
   */
  public role findbyroleid(string roleid){
    return rolerepository.findone(integer.parseint(roleid));
  }
 
  /**
   * 保存角色信息
   * @param role
   */
  public void dosave(role role){
    rolerepository.save(role);
  }
}

菜单service类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package org.muses.jeeplatform.service;
import org.muses.jeeplatform.annotation.rediscache;
import org.muses.jeeplatform.common.rediscachenamespace;
import org.muses.jeeplatform.core.dao.repository.admin.menutreerepository;
import org.muses.jeeplatform.core.entity.admin.menu;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;
import java.util.list;
/**
 * created by nicky on 2017/6/17.
 */
@service
public class menutreeservice {
 
  @autowired
  menutreerepository menutreerepository;
 
  /**
   * 查询所有的菜单
   * @return
   */
  @transactional
  //@rediscache
  public list<menu> findall(){
    return menutreerepository.findall();
  }
}

在controller类里通过角色id获取该角色可以查看的菜单:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
   * 跳转到角色授权页面
   * @param roleid
   * @param model
   * @return
   */
  @requestmapping(value = "/goauthorise" )
  public string goauth(@requestparam string roleid, model model){
    list<menu> menulist = menutreeservice.findall();
    role role = roleservice.findbyroleid(roleid);
    set<permission> haspermissions = null;
    if(role != null){
      haspermissions = role.getpermissions();
    }
    for (menu m : menulist) {
      for(permission p : haspermissions){
        if(p.getmenu().getmenuid()==m.getmenuid()){
          m.sethassubmenu(true);
        }
      }
    }
    model.addattribute("roleid" , roleid);
    jsonarray jsonarray = jsonarray.fromobject(menulist);
    string json = jsonarray.tostring();
    json = json.replaceall("menuid","id").replaceall("parentid","pid").
        replaceall("menuname","name").replaceall("hassubmenu","checked");
    model.addattribute("menus",json);
    return "admin/role/role_auth";
  }

在前端通过ztree实现树形菜单展示,通过勾选然后实现角色授权:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<%@ page contenttype="text/html; charset=utf-8" pageencoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
  string path = request.getcontextpath();
  string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>
<!doctype html>
<html lang="zh-cn">
<head>
  <base href="<%=basepath %>" rel="external nofollow" >
  <meta charset="utf-8" />
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>insert title here</title>
  <!-- 引入jquery库 start -->
  <script type="text/javascript" src="${basepath}static/js/jquery-1.8.3.js"></script>
  <!-- 引入jquery库 end -->
  <script type="text/javascript" src="<%=basepath%>plugins/zdialog/zdialog.js"></script>
  <script type="text/javascript" src="<%=basepath%>plugins/zdialog/zdrag.js"></script>
  <script type="text/javascript" src="<%=basepath%>plugins/zdialog/zprogress.js"></script>
  <link rel="stylesheet" href="<%=basepath%>plugins/ztree/3.5/ztreestyle.css" rel="external nofollow" type="text/css">
  <script type="text/javascript" src="<%=basepath%>plugins/ztree/3.5/jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="<%=basepath%>plugins/ztree/3.5/jquery.ztree.core.js"></script>
  <script type="text/javascript" src="<%=basepath%>plugins/ztree/3.5/jquery.ztree.excheck.js"></script>
  <script type="text/javascript">
    <!--
    var setting = {
      check: {
        enable: true
      },
      data: {
        simpledata: {
          enable: true
        }
      },
      callback:{
        onclick: {
 
        }
      }
    };
 
 
    /*[
     { id:1, pid:0, name:"随意勾选 1", open:true},
     { id:11, pid:1, name:"随意勾选 1-1", open:true},
     { id:12, pid:1, name:"随意勾选 1-2", open:true}
     ];*/
 
    var json = ${menus};
    var znodes = eval(json);
 
    var code;
 
    function setcheck() {
      var ztree = $.fn.ztree.getztreeobj("treedemo"),
        py = $("#py").attr("checked")? "p":"",
        sy = $("#sy").attr("checked")? "s":"",
        pn = $("#pn").attr("checked")? "p":"",
        sn = $("#sn").attr("checked")? "s":"",
        type = { "y":py + sy, "n":pn + sn};
      ztree.setting.check.chkboxtype = type;
      showcode('setting.check.chkboxtype = { "y" : "' + type.y + '", "n" : "' + type.n + '" };');
    }
    function showcode(str) {
      if (!code) code = $("#code");
      code.empty();
      code.append("<li>"+str+"</li>");
    }
 
    $(document).ready(function(){
      $.fn.ztree.init($("#treedemo"), setting, znodes);
      setcheck();
      $("#py").bind("change", setcheck);
      $("#sy").bind("change", setcheck);
      $("#pn").bind("change", setcheck);
      $("#sn").bind("change", setcheck);
    });
    //-->
 
    function dialogclose()
    {
      parentdialog.close();
    }
 
    function dosave() {
      var ztree = $.fn.ztree.getztreeobj("treedemo");
      var nodes = ztree.getcheckednodes();
      var tmpnode;
      var ids = "";
      for(var i=0; i<nodes.length; i++){
        tmpnode = nodes[i];
        if(i!=nodes.length-1){
          ids += tmpnode.id+",";
        }else{
          ids += tmpnode.id;
        }
      }
      var roleid = ${roleid};
      var params = roleid +";"+ids;
      alert(ids);
      $.ajax({
        type: "post",
        url: 'role/authorise.do',
        data: {params:params,tm:new date().gettime()},
        datatype:'json',
        cache: false,
        success: function(data){
          if("success" == data.result){
            alert('授权成功!请重新登录!');
            parent.location.reload();
            dodialogclose();
          }else{
            alert("授权失败!");
          }
        }
      });
    }
 
  </script>
</head>
<body >
<div class="content_wrap">
  <div class="ztreedemobackground left">
    <ul id="treedemo" class="ztree"></ul>
  </div>
</div>
  
<input type="button" onclick="dosave()" value="保存" class="buttonstyle" />
<input onclick="dialogclose();" class="buttonstyle" type="button" value="关闭" />
</body>
</html>

SpringMVC+ZTree实现树形菜单权限配置的方法

team的github开源项目链接:https://github.com/u014427391/jeeplatform

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/fb49b3aa129f