前言
本文详细讲解了如何根据不同的用户登陆,进入的后台管理系统界面发生不一样的变化
在日常办公和会议管理中,提高工作效率和简化操作流程是每个组织都追求的目标。而利用Layui框架的强大功能,特别是通过打造智能化的左侧权限菜单列表,可以为会议OA管理带来卓越的效果。在本文中,我们将揭秘Layui的神技,探讨如何利用其轻松构建动态可控的会议OA左侧权限菜单列表,让您的工作更高效、更便捷。无论你是会议组织者还是会议参与者,都值得掌握这一利器,提升工作效率,打造智能化会议管理系统。
1、下载和学习使用layui
http://layui.org.cn/index.html
2、权限菜单--数据库分析
在做权限之前,我们用生活的例子来看待,我们往往可以在生活中发现,不同级别的人登陆进入后天管理系统,看到的是不同的功能模块,就比如我们财务人员,登陆后台管理系统是无法进行对公司人员的管理的,
2.1、user表结构
一个 rid 可以对应多个 id ,翻译过来就是,每个人都会有一个角色,但是角色可以对应多个人,也就是说,张三也可以是管理员,李四也可以是管理员,用户登陆的时候,拿到其rid进行判断---后面再说
2.2、permission表结构
在权限表中,我们可以看到有一个id还有pid,同样,pid和id也是一对多的关系,举个例子,我们的qq列表中有个好友分组,一些人属于特别关系,一些人属于其他等等,这里就跟qq一样,假如有两条数据,一条就命名为特别关心,一条命名为xxx,那么特别关心的数据就是
id:1--pid:-1--name:特别关心
id:2--pid:1--name:xxx
对照上面的数据可以发现,子模块的pid对应的就是父级模块id,但是如果是一级模块,那么我们就将其pid设置为-1
2.3、permission-role表结构
在此表中只有两个字段,但是两个字段都非常重要,他将用户表和权限表联合起来了,权限的关键也在于这张表,根据上面两个表的解释,现在走一遍完整的例子
用户登录进入---后台接收---查询到用户---获取其rid---放到permission-role表中查询对应的权限模块id(外键,关联权限表中的id)
就比如我是管理员id1,我的拥有的权限id是,-1,1,21,33.。。
那么此时这张表中的数据就是
1 -1
1 1
1 21
1 33
3、权限菜单演示
对照之后,我们可以很明显的看到zq这个用户登录进去时,是没有系统管理这个模块的,但是admin用户有,这就是因为在role-Permission这张表中,给他们对应的每个角色分配的权限
4、代码实现--登录流程
4.1、login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="common/public.jsp"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>后台登陆界面</title> <script src="static/js/login.js"></script> <style> body { background-color: #f5f5f5; font-family: Arial, sans-serif; } .container { display: flex; justify-content: center; align-items: center; height: 100vh; } .login-box { background-color: #fff; border-radius: 4px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); padding: 40px; text-align: center; } .login-box h2 { margin-bottom: 20px; color: #333; } .login-box input[type="text"], .login-box input[type="password"] { width: 100%; padding: 12px 20px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-size: 16px; } .login-box input[type="button"] { background-color: #4CAF50; color: #fff; border: none; padding: 12px 20px; border-radius: 4px; cursor: pointer; font-size: 16px; } .login-box input[type= "button]:hover { background-color: #45a049; } </style> </head> <body> <div class="container"> <div class="login-box"> <h2>后台登录</h2> <form> <input id="username" type="text" placeholder="用户名" required> <input id="password" type="password" placeholder="密码" required> <input id="login" type="button" value="登录"> </form> </div> </div> </body> </html>
4.2、login.js
layui.use(['jquery','layer'], function(){ var $ = layui.jquery, layer=layui.layer; $('#login').click(function(){ $.ajax({ url: 'User.action?methodName=login', data: { loginName: $("#username").val(), pwd: $("#password").val() }, dataType: 'text', type: 'post', success: function(data){ console.log(data) if(data=='登陆成功'){ layer.msg('登录成功', { icon: 1, time: 2000 }, function(){ location.href = "index.jsp"; }); } else { layer.msg('登录失败', { icon: 2, time: 2000 }); } } }); }) });
4.3、userServlet
package Servlet; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; import com.zking.util.PageBean; import com.zking.util.R; import com.zking.util.ResponseUtil; import Dao.Userdao; import Entity.User; public class UserServlet extends ActionSupport implements ModelDriver<User>{ private User user= new User(); private PageBean page= new PageBean(); private Userdao ud= new Userdao(); public String login(HttpServletRequest req, HttpServletResponse resp) throws Exception { // 调用dao中的方法 User users = ud.login(user, page); if(users!=null) { req.getSession().setAttribute("user", users); resp.getWriter().write("登陆成功"); }else { resp.getWriter().write("登陆失败"); } return null; } }
4.4、userdao
package Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.zking.util.BaseDao; import com.zking.util.DBAccess; import com.zking.util.PageBean; import com.zking.util.StringUtils; import Entity.Role_permission; import Entity.User; public class Userdao extends BaseDao<User>{ // 登陆的方法 public User login(User u,PageBean pagebean) throws Exception { String sql="select * from t_oa_user where loginName='"+u.getLoginName()+"' and pwd='"+u.getPwd()+"'"; List<User> users = super.executeQuery(sql, User.class, pagebean); return users == null || users.size() == 0 ? null : users.get(0); } }
5、代码实现--主界面加载流程
5.1、index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/common/public.jsp"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>后台管理主界面</title> <script src="static/js/index.js" ></script> <style> .layui-tab-title>li:first-child>i{ display:none; } .layui-tab>.layui-tab-content{ padding:0px; } body,html{ padding:0px; margin:0px; overflow:hidden; } .layui-nav-tree .layui-nav-child dd.layui-this, .layui-nav-tree .layui-nav-child dd.layui-this a, .layui-nav-tree .layui-this, .layui-nav-tree .layui-this>a, .layui-nav-tree .layui-this>a:hover { background-color: #2F4056; color: #fff; } </style> </head> <c:if test="${empty user }"> <jsp:forward page="login.jsp"></jsp:forward> </c:if> <body> <div class="layui-layout layui-layout-admin"> <div class="layui-header "> <div class="layui-logo layui-hide-xs">会议OA</div> <!-- 头部区域(可配合layui 已有的水平导航) --> <!-- <ul class="layui-nav layui-layout-left"> 移动端显示 <li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft"> <i class="layui-icon layui-icon-spread-left"></i> </li> Top导航栏 <li class="layui-nav-item layui-hide-xs"><a href="">nav 1</a></li> <li class="layui-nav-item layui-hide-xs"><a href="">nav 2</a></li> <li class="layui-nav-item layui-hide-xs"><a href="">nav 3</a></li> <li class="layui-nav-item"> <a href="javascript:;">nav groups</a> <dl class="layui-nav-child"> <dd><a href="">menu 11</a></dd> <dd><a href="">menu 22</a></dd> <dd><a href="">menu 33</a></dd> </dl> </li> </ul> --> <!-- 个人头像及账号操作 --> <ul class="layui-nav layui-layout-right"> <li class="layui-nav-item layui-hide layui-show-md-inline-block"> <a href="javascript:;"> <img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg" class="layui-nav-img"> ${user.name} </a> <dl class="layui-nav-child"> <dd><a href="login.jsp">Sign out</a></dd> </dl> </li> <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect> <a href="javascript:;"> <i class="layui-icon layui-icon-more-vertical"></i> </a> </li> </ul> </div> <div class="layui-side layui-bg-black"> <div class="layui-side-scroll"> <!-- 左侧导航区域(可配合layui已有的垂直导航) --> <ul id="menu" class="layui-nav layui-nav-tree " lay-filter="menu"> </ul> </div> </div> <div class="layui-body"> <!-- 内容主体区域 --> <div style="padding: 15px;"> <div class="layui-tab" lay-filter="openTab" lay-allowclose="true"> <ul class="layui-tab-title"> <li class="layui-this" lay-id="-1">首页</li> </ul> <div class="layui-tab-content"> <div class="layui-tab-item layui-show">首页内容</div> </div> </div> </div> </div> <div class="layui-footer" style="text-align: center;"> <!-- 底部固定区域 --> Copyright © 2022-2024 版权所有 </div> </div> </body> </html>
5.2、index.js
let layer,$,element; layui.use(['jquery', 'layer', 'element'], function(){ layer = layui.layer ,$ = layui.jquery ,element = layui.element; $.ajax({ url:'Index.action?methodName=tree' ,dataType:'json' ,success:function(data){ let htmlstr = ''; console.log(data) $.each(data,function(i,n){ htmlstr += '<li class="layui-nav-item layui-nav-itemed ">'; htmlstr += ' <a class="" href="javascript:;">'+n.text+'</a>'; if(n.hasChildren){ let children = n.children; console.log(children) htmlstr += '<dl class="layui-nav-child">'; $.each(children,function(index,node){ htmlstr += '<dd class=""><a href="javascript:;" onclick="openTab(\''+node.text+'\',\''+node.attributes.self.url+'\',\''+node.id+'\');" >'+node.text+'</a></dd>'; }); htmlstr += '</dl>'; } htmlstr += '</li>'; }) console.log(htmlstr) $("#menu").html(htmlstr); //渲染ul标签 element.render('#menu'); } }); }); function openTab(title,url,id){ let $node = $("li[lay-id='"+id+"']"); // 此时点击菜单,会自动生成上面的标签,对应的id生成对应的标签, // 抓到这个标签进行判断,如果为0,打开一个新的tab内嵌一个网页 if($node.length == 0){ element.tabAdd('openTab', { title: title ,content: "<iframe frameborder='0' src='"+url+"' scrolling='auto' style='width:100%;height:100%;'></iframe>" ,id: id }) } // 如果不为0,那么就切换对应id的tab卡 element.tabChange('openTab', id); //切换到 }
5.3、Indexservlet
package Servlet; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zking.framework.ActionSupport; import com.zking.util.R; import com.zking.util.ResponseUtil; import com.zking.util.TreeVo; import Dao.Permissiondao; import Entity.Permission; import Entity.User; public class IndexServlet extends ActionSupport{ public String tree(HttpServletRequest req, HttpServletResponse resp) throws Exception { User u = (User) req.getSession().getAttribute("user"); Permissiondao p= new Permissiondao(); List<TreeVo<Permission>> menus = p.menus(u); System.out.println(menus); ResponseUtil.writeJson(resp, menus); return null; } }
5.4、dao方法
// 根据模块id查询整个模块 public Permission querypermissionby_id(int id) { String sql="select * from t_oa_permission where id='"+id+"'"; Connection conn=null; PreparedStatement ps= null; ResultSet rs=null; Permission p=null; try { conn=DBAccess.getConnection(); ps=conn.prepareStatement(sql); rs=ps.executeQuery(); if(rs.next()) { p= new Permission(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getLong(5), rs.getInt(6), rs.getLong(7)); } } catch (Exception e) { e.printStackTrace(); } return p; } ========================================================================================== // 根据指定用户查出对应的所有模块 public List<Permission> executeQuery(User u) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Role_permission r = null; List<Permission> list = new ArrayList<>(); System.out.println( u.getRid()); String sql = "select * from t_oa_role_permission where rid = '" + u.getRid() + "'"; try { conn=DBAccess.getConnection(); ps=conn.prepareStatement(sql); rs=ps.executeQuery(); while(rs.next()) { r = new Role_permission(rs.getInt(1),new Permissiondao().querypermissionby_id(rs.getInt(2))); // 将查询到的角色权限对象,拿出权限对象全部放入新的集合 list.add(r.getPid()); } } catch (Exception e) { e.printStackTrace(); } return list; } ================================================================================== //调用treevo进行分级 public List<TreeVo<Permission>> menus(User u) throws Exception{ List<Permission> list =new Role_permissiondao().executeQuery(u); List<TreeVo<Permission>> treeVos = new ArrayList<TreeVo<Permission>>(); for (Permission p : list) { TreeVo<Permission> vo = new TreeVo<>(); vo.setId(p.getId()+""); vo.setParentId(p.getPid()+""); vo.setText(p.getName()); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("self", p); vo.setAttributes(attributes ); treeVos.add(vo); } // TreeVo<Permission> build = BuildTree.build(treeVos); List<TreeVo<Permission>> buildList = BuildTree.buildList(treeVos, "-1"); return buildList; }
6、代码实现--前期准备(懒得改目录了兄弟们🤣🤣🤣)
6.1、user类
package Entity; public class User { private long id; private String name; private String loginName; private String pwd; private long rid; public User() { // TODO Auto-generated constructor stub } public User(long id, String name, String loginName, String pwd, long rid) { super(); this.id = id; this.name = name; this.loginName = loginName; this.pwd = pwd; this.rid = rid; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public long getRid() { return rid; } public void setRid(long rid) { this.rid = rid; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", loginName=" + loginName + ", pwd=" + pwd + ", rid=" + rid + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + ((loginName == null) ? 0 : loginName.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((pwd == null) ? 0 : pwd.hashCode()); result = prime * result + (int) (rid ^ (rid >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id != other.id) return false; if (loginName == null) { if (other.loginName != null) return false; } else if (!loginName.equals(other.loginName)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (pwd == null) { if (other.pwd != null) return false; } else if (!pwd.equals(other.pwd)) return false; if (rid != other.rid) return false; return true; } }
6.2、permission类
package Entity; public class Permission { private long id; private String name; private String description; private String url; private long pid; private int ismenu; private long displayno; public Permission() { // TODO Auto-generated constructor stub } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getPid() { return pid; } public void setPid(long pid) { this.pid = pid; } public int getIsmenu() { return ismenu; } public void setIsmenu(int ismenu) { this.ismenu = ismenu; } public long getDisplayno() { return displayno; } public void setDisplayno(long displayno) { this.displayno = displayno; } public Permission(long id, String name, String description, String url, long pid, int ismenu, long displayno) { super(); this.id = id; this.name = name; this.description = description; this.url = url; this.pid = pid; this.ismenu = ismenu; this.displayno = displayno; } @Override public String toString() { return "Permission [id=" + id + ", name=" + name + ", description=" + description + ", url=" + url + ", pid=" + pid + ", ismenu=" + ismenu + ", displayno=" + displayno + "]"; } }
6.3、permission_role类
package Entity; public class Role_permission { private int rid; //用户表中的角色id private Permission pid;//权限表中的模块id public Role_permission() { // TODO Auto-generated constructor stub } public Role_permission(int rid, Permission pid) { super(); this.rid = rid; this.pid = pid; } public int getRid() { return rid; } public void setRid(int rid) { this.rid = rid; } public Permission getPid() { return pid; } public void setPid(Permission pid) { this.pid = pid; } @Override public String toString() { return "Role_permission [rid=" + rid + ", pid=" + pid + "]"; } }
6.4、treevo类
package com.zking.util; 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(); } @Override public String toString() { return "TreeVo [id=" + id + ", text=" + text + ", state=" + state + ", checked=" + checked + ", attributes=" + attributes + ", children=" + children + ", parentId=" + parentId + ", hasParent=" + hasParent + ", hasChildren=" + hasChildren + "]"; } }
6.5、BuildTree类
package com.zking.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class BuildTree { /** * 默认-1为顶级节点 * @param nodes * @param <T> * @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(); if (pid == null || "-1".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; } } } 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; } }