标签:
Web应用——驾培管理系统之系统—权限分配(作者:小圣)
本节博文将向大家介绍本次Web应用之权限分配。
笔者会把大概实现过程贴出来,有看不懂过程且需要项目源码的请戳:http://download.csdn.net/detail/xie_xiansheng/9486872,需要数据库表格的请留言。有些小细节没完善,有些代码冗余,初学请见谅!本节博文需要json格式的第三方jar包,有需要的请戳:http://download.csdn.net/detail/xie_xiansheng/9488231 或者 http://download.csdn.net/detail/xie_xiansheng/9486876下载自己对应jdk版本的json-lib包,笔者自身是jdk13版本,还另外提供了jdk15版本,需要的可以去下载。
何为权限分配,就是本次驾培系统设置一个超级管理人员,这个管理人员能给在本平台上的所有用户进行权限分配。可以让用户登录后根据超级管理人员所分配的权限,给予与之相对应的权限操作。本次权限分配用了两个oracle数据表,一个是所有权限的表格,即全部权限都存在里面,并且设置权限的ID和等级。另一个是用户权限表格,根据超级管理人员所分配的权限,在用户权限表格上增删权限ID。说了这么多,不知道大家能不能明白,先上效果图。
权限分配演示一:超管登录,对admin用户进行权限分配。admin用户登录后,只能操作个人和系统管理。
权限分配演示二:超管登录,对hongxing用户进行权限分配。hongxing用户登录后,只能操作个人和系统管理。
看完上面两个gif图,大家应该明白此次实现的功能是什么了。本次权限分配用了一个第三方插件:Ztree,实现权限的树状列表。
下面给大家展现一下Ztree的demo,以便明白笔者是怎么实现这个权限分配的.
这是Ztree插件附带的demo,点击右键审查页面代码,可以看到:树状结构由一个zNodes实现
<link rel="stylesheet" href="../../../css/demo.css" type="text/css"> <link rel="stylesheet" href="../../../css/zTreeStyle/zTreeStyle.css" type="text/css"> <script type="text/javascript" src="../../../js/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="../../../js/jquery.ztree.core-3.5.js"></script> <script type="text/javascript" src="../../../js/jquery.ztree.excheck-3.5.js"></script> <!-- <script type="text/javascript" src="../../../js/jquery.ztree.exedit-3.5.js"></script> --> <SCRIPT type="text/javascript"> <!-- var setting = { check: { enable: true }, data: { simpleData: { enable: true } } }; var zNodes =[ { id:1, pId:0, name:"个人管理 1", open:true}, { id:3, pId:1, name:"随意勾选 1-1", open:true}, { id:5, pId:1, name:"随意勾选 1-1-1"}, { id:112, pId:11, name:"随意勾选 1-1-2"}, { id:12, pId:1, name:"随意勾选 1-2", open:true}, { id:121, pId:12, name:"随意勾选 1-2-1"}, { id:122, pId:12, name:"随意勾选 1-2-2"}, { id:2, pId:0, name:"随意勾选 2", checked:true, open:true}, { id:21, pId:2, name:"随意勾选 2-1"}, { id:22, pId:2, name:"随意勾选 2-2", open:true}, { id:221, pId:22, name:"随意勾选 2-2-1", checked:true}, { id:222, pId:22, name:"随意勾选 2-2-2", checked:false}, { id:23, pId:2, name:"随意勾选 2-3"}, ]; 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); }); //--> </SCRIPT> </HEAD> <BODY> <div class="content_wrap"> <div class="zTreeDemoBackground left"> <ul id="treeDemo" class="ztree"></ul> </div> </div>
全部权限的表格:
用户所有权限的表格:超管的user_id是1,他拥有全部权限ID
接下来请看我们的UserServlet:
public class UserServlet extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); String task = req.getParameter("task"); HttpSession session = req.getSession(); //从登陆的传的session获取到用户信息 UserBean userBean = (UserBean)session.getAttribute("Logindo"); UserDao userDao = DaoFactory.getUserDao(); PrintWriter writer = resp.getWriter(); if("logout".equals(task)){ session = req.getSession(); session.invalidate(); req.getRequestDispatcher("index.jsp").forward(req, resp); }else if("permission".equals(task)){ //跳转到权限分配jsp int pagenum = Integer.parseInt(req.getParameter("pagenum")); int count = userDao.countUser(); PageBean pageBean = new PageBean(); pageBean.findPageBean(count, pagenum); List<UserBean> userBeans =userDao.findPage(pageBean); req.setAttribute("pageBean", pageBean); req.setAttribute("userBeans", userBeans); req.getRequestDispatcher("jsp/sysmanager/permission.jsp").forward(req, resp); }else if("delivery".equals(task)){ //权限分配业务逻辑 //TODO int deliveryUserId = Integer.parseInt(req.getParameter("userid")); userBean = userDao.findUser_ById(deliveryUserId); session.setAttribute("func_userBean", userBean); req.getRequestDispatcher("jsp/sysmanager/testfunc.jsp").forward(req, resp); //jsp点击权限分配 }else if("test".equals(task)){ int user_id = Integer.parseInt(req.getParameter("user_id")) ; //获取全部的权限列表 List<FuncBean> funcList = DaoFactory.getFuncDao().getFunc_Already(); //根据用户ID获取他所有的权限 List<FuncBean> userList = DaoFactory.getFuncDao().getFunc_ALL(user_id); int userid = userBean.getUser_id(); //获取出id,pid(权限父ID),name(权限名),open(是否展开),checked(默认选中)等属性 List<FunctionBean> functionBeans = new ArrayList<FunctionBean>(); //对全部权限列表进行迭代 for (FuncBean Bean : funcList) { FunctionBean functionBean = new FunctionBean(); //将权限表的所有信息set进去 functionBean.setId(Bean.getFunc_id()); functionBean.setpId(Bean.getFunc_pid()); functionBean.setName(Bean.getFunc_name()); //如果权限列表的父id为0,则默认展开 if(Bean.getFunc_pid()==0){ functionBean.setOpen(true); }else{ functionBean.setOpen(false); } int flag = 0; //对用户已有权限列表进行迭代 for (FuncBean itemBean : userList) { //如果用户已有权限ID与所有权限表的权限ID相等,则默认选中 if(itemBean.getFunc_id()==Bean.getFunc_id()){ flag = 1; functionBean.setChecked(true); } } //否则不选中 if(flag == 0){ functionBean.setChecked(false); } //将结果存到List<FunctionBean> functionBeans中 functionBeans.add(functionBean); } //转换为JSON格式传到页面,转换为JSON格式,结果就是上文所需的zNodes格式[{id: ,pid: ,name:'',open:ture/false,checked:true/false}],不明白可以留言 JSONArray funcjson = JSONArray.fromObject(functionBeans); writer.write(funcjson.toString()); writer.flush(); //权限分配完成点击提交 }else if("finish".equals(task)){ //获取JSP页面传来的user_id int user_id = Integer.parseInt(req.getParameter("user_id")) ; //获取JSP页面传来的权限ID的字符串 String rightsId = req.getParameter("rightsId"); //截取成单个字符串数组 String [] stringArr= rightsId.split(","); //String stringArr[] = req.getParameterValues("rightsId"); //删除对应用户已有的权限 DaoFactory.getFuncDao().deleteFunc_All(user_id); for (int i = 0; i < stringArr.length; i++) { if(!stringArr[i].equals("")){ //如果权限ID不为空,则将权限添加进数据表 int func_id = Integer.valueOf(stringArr[i]) ; DaoFactory.getFuncDao().addFunc_ByUserId(user_id,func_id); } } userBean = userDao.findUser_ById(user_id); req.setAttribute("msg", "分配成功,已保存!"); session.setAttribute("func_userBean", userBean); req.getRequestDispatcher("jsp/sysmanager/testfunc.jsp").forward(req, resp); //导航-》关于/我的 }else if("about".equals(task)){ int driving_id = userBean.getDriving_id(); String driving_name = DaoFactory.getDrivingSchDao().findDrivName_ById(driving_id); ApkBean apkBean = DaoFactory.getRoleDao().findApk_ByNewOne(); req.setAttribute("apkBean", apkBean); req.setAttribute("driving_name", driving_name); req.setAttribute("userBean", userBean); req.getRequestDispatcher("jsp/sysmanager/about.jsp").forward(req, resp); } } }
这是我们的权限分配的JSP:
<%@ page language="java" import="java.util.*,org.great.bean.*" pageEncoding="utf-8"%> <%@page import="org.great.dao.DaoFactory"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'usermanager.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <link rel="stylesheet" type="text/css" href="<%=basePath%>/background/Style/skin.css" /> <script type="text/javascript" src="<%=basePath%>/zTree/js/jquery-1.4.4.min.js"> </script> <link rel="stylesheet" href="<%=basePath%>/zTree/css/demo.css" type="text/css"> <link rel="stylesheet" href="<%=basePath%>/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css"> <script type="text/javascript" src="<%=basePath%>/zTree/js/jquery.ztree.core-3.5.js"> </script> <script type="text/javascript" src="<%=basePath%>/zTree/js/jquery.ztree.excheck-3.5.js"> </script> </head> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <!-- 头部开始 --> <tr> <td width="17" valign="top" background="<%=basePath%>/background/Images/mail_left_bg.gif"> <img src="<%=basePath%>/background/Images/left_top_right.gif" width="17" height="29" /> </td> <td valign="top" background="<%=basePath%>/background/Images/content_bg.gif"> <table width="100%" height="31" border="0" cellpadding="0" cellspacing="0" background="<%=basePath%>/background/<%=basePath%>/background/Images/content_bg.gif"> <tr><td height="31"><div class="title" style="color: red">权限分配</div></td></tr> </table> </td> <td width="16" valign="top" background="<%=basePath%>/background/Images/mail_right_bg.gif"><img src="<%=basePath%>/background/Images/nav_right_bg.gif" width="16" height="29" /></td> </tr> <!-- 中间部分开始 --> <tr> <!--第一行左边框--> <td valign="middle" background="<%=basePath%>/background/Images/mail_left_bg.gif"> </td> <!--第一行中间内容--> <td valign="top" bgcolor="#F7F8F9"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <!-- 空白行--> <tr><td colspan="2" valign="top"> </td><td> </td><td valign="top"> </td></tr> <tr> <td colspan="4"> <table> <tr> <td width="100" align="center"><img src="<%=basePath%>/background/Images/mime.gif" /></td> <td valign="bottom"><h3 style="letter-spacing:1px;color: blue">在这里,您可以修改用户的权限</h3></td> </tr> </table> </td> </tr> <!-- 一条线 --> <tr> <td height="40" colspan="4"> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC"> <tr><td></td></tr> </table> </td> </tr> <!-- 产品列表开始 --> <%UserBean userBean = (UserBean)session.getAttribute("func_userBean"); int user_id = userBean.getUser_id(); %> <tr> <td width="2%"> </td> <td width="96%"> <table width="100%"> <tr> <td colspan="2"> <table width="100%" class="cont tr_color"> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> <tr align="right" class="d"> <td colspan="2" style="width: 300px"> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <h2>您想对<span style="color: red"><%=userBean.getUser_name() %></span>分配什么样的权限?</h2> </td> <td> <form action="user.do?task=finish" name="checkForm" method="post" > <div class="zTreeDemoBackground left"> <ul id="treeDemo" class="ztree"></ul> <input type="hidden" id="user_id" name="user_id" value="<%=user_id%>"> </div> <div style="margin-right: 120px"> <br> <input type="hidden" name="rightsId" id="rightsId" /> <input type="submit" value="保存" onclick="onCheck()" /> </div> </form> </td> <td colspan="2" style="width: 300px"> </tr> </table> </td> </tr> </table> </td> <td width="2%"> </td> </tr> <!-- 产品列表结束 --> <tr> <td height="40" colspan="4"> <table width="100%" height="1" border="0" cellpadding="0" cellspacing="0" bgcolor="#CCCCCC"> <tr><td></td></tr> </table> </td> </tr> <tr> <td width="2%"> </td> <td width="51%" class="left_txt"> <img src="<%=basePath%>/background/Images/icon_mail.gif" width="16" height="11"> 客户服务邮箱:870873201@qq.com<br /> <img src="<%=basePath%>/background/Images/icon_phone.gif" width="17" height="14"> 官方网站:<a href="http://my.csdn.net/xie_xiansheng" target="_blank">作者博客</a> </td> <td> </td><td> </td> </tr> </table> </td> <td background="<%=basePath%>/background/Images/mail_right_bg.gif"> </td> </tr> <!-- 底部部分 --> <tr> <td valign="bottom" background="<%=basePath%>/background/Images/mail_left_bg.gif"> <img src="<%=basePath%>/background/Images/buttom_left.gif" width="17" height="17" /> </td> <td background="<%=basePath%>/background/Images/buttom_bgs.gif"> <img src="<%=basePath%>/background/Images/buttom_bgs.gif" width="17" height="17"> </td> <td valign="bottom" background="<%=basePath%>/background/Images/mail_right_bg.gif"> <img src="<%=basePath%>/background/Images/buttom_right.gif" width="16" height="17" /> </td> </tr> </table> </body> <SCRIPT type="text/javascript"> var user_id = $("#user_id").val(); var setting = { check: { enable: true, chkStyle: "checkbox", chkboxType: { "Y": "ps", "N": "ps" } }, data: { simpleData: { enable: true } }, callback:{ onCheck:onCheck } }; $(document).ready(function() { $.ajax( { url : "user.do?task=test&suibian=hehe&user_id="+user_id, type : "get", dataType : "test", success : function(data){ initZtree(data); } }); }); function initZtree(data) { var zNodes = JSON.parse(data); var zTreeObj = $.fn.zTree.init($('#treeDemo'), setting, zNodes); } function onCheck(e,treeId,treeNode){ var treeObj=$.fn.zTree.getZTreeObj("treeDemo"), nodes=treeObj.getCheckedNodes(true), v=""; for(var i=0;i<nodes.length;i++){ v+=nodes[i].id + ","; }//这会返回我们选中的节点给Servlet,然后在Servlet进行操作,先删除对应USER_ID的全部权限,然后选中的权限添加进去 $("#rightsId").attr("value", v); } var msg = "<%=request.getAttribute("msg")%>"; if("null"!=msg){ alert(msg); } </SCRIPT> </html>
package org.great.daoimpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.great.bean.FuncBean; import org.great.dao.FuncDao; import org.great.util.DBUtils; public class FuncDaoImpl implements FuncDao{ private PreparedStatement pre = null; private ResultSet rs = null; /** 获得权限表数据*/ public List<FuncBean> getFunc_ALL(int user_id){ List<FuncBean> list = new ArrayList<FuncBean>(); Connection conn = DBUtils.getConn(); String sql = "select f.func_id,f.func_pid,f.func_name,f.func_url,f.func_level from t_function f," + "t_user_function rf where f.func_id = rf.func_id and rf.user_id = ?"; try { pre = conn.prepareStatement(sql); pre.setInt(1, user_id); rs = pre.executeQuery(); while(rs.next()){ FuncBean funcBean = new FuncBean(); funcBean.setFunc_id(rs.getInt(1)); funcBean.setFunc_pid(rs.getInt(2)); funcBean.setFunc_name(rs.getString(3)); funcBean.setFunc_url(rs.getString(4)); funcBean.setFunc_level(rs.getString(5)); list.add(funcBean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ DBUtils.close(conn, pre, rs); } return list; } //删除用户已有权限 public void deleteFunc_All(int userId) { Connection conn = DBUtils.getConn(); String sql = "delete t_user_function where user_id = ?"; try { pre = conn.prepareStatement(sql); pre.setInt(1, userId); rs = pre.executeQuery(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ DBUtils.close(conn, pre, rs); } } //根据超级管理员分配的权限添加进权限表 public void addFunc_ByUserId(int userId,int func_id) { Connection conn = DBUtils.getConn(); String sql = "insert into t_user_function values(?,?)"; try { pre = conn.prepareStatement(sql); pre.setInt(1, userId); pre.setInt(2, func_id); rs = pre.executeQuery(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ DBUtils.close(conn, pre, rs); } } }
标签:
原文地址:http://blog.csdn.net/xie_xiansheng/article/details/51140581