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

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

概述计划在开源项目里加入权限配置的功能,打算加入zTree实现树形结构。Team的Github开源项目链接:https://github.com/u014427391/jeeplatform欢迎star(收藏)

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

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

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

zTree下载链接:http://www.treejs.cn/v3/main.php#_zTreeInfo

 

角色信息实体类:

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")@Entitypublic 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);  }}

权限信息实体类:

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")@Entitypublic 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,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来实现

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")@Entitypublic 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接口

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接口

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类:

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. */@Servicepublic 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类:

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. */@Servicepublic class MenuTreeService {  @autowired  MenuTreeRepository menuTreeRepository;  /**   * 查询所有的菜单   * @return   */  @Transactional  //@RedisCache  public List<Menu> findAll(){    return menuTreeRepository.findAll();  }}

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

/**   * 跳转到角色授权页面   * @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实现树形菜单展示,通过勾选然后实现角色授权:

<%@ 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",{ ID:12,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 >  <div >    <ul ID="treeDemo" ></ul>  </div></div>  <input type="button" onClick="doSave()" value="保存"  /><input onClick="dialogClose();"  type="button" value="关闭" /></body></HTML>

 

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的SpringMVC+ZTree实现树形菜单权限配置的方法全部内容,希望文章能够帮你解决SpringMVC+ZTree实现树形菜单权限配置的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1224147.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存