权限管理

分类: Web开发

最近由于项目不是很紧所以总结了之前做了n遍的权限管理功能。以便之后系统copy之用。
之前做过权限绑定给具体人的操作,而这次做的是权限绑定给角色,人员去选择角色。
废话不多说,先看效果
1.页面展示(新建角色,绑定权限)
权限管理

2.权限管理数据库设计

  

点击(此处)折叠或打开

  1. -- ----------------------------
  2. -- Table structure for `account` 登录账号表
  3. -- ----------------------------
  4. DROP TABLE IF EXISTS `account`;
  5. CREATE TABLE `account` (
  6.   `id` bigint(20) NOT NULL AUTO_INCREMENT,
  7.   `uid` bigint(20) NOT NULL,
  8.   `accId` varchar(200) NOT NULL,
  9.   `pw` varchar(200) NOT NULL,
  10.   `loginTime` datetime DEFAULT NULL,
  11.   `isBenefit` smallint(6) NOT NULL DEFAULT '1',
  12.   `remark` varchar(500) DEFAULT NULL,
  13.   `createTime` datetime DEFAULT NULL,
  14.   `createUser` bigint(20) DEFAULT NULL,
  15.   `updateTime` datetime DEFAULT NULL,
  16.   `updateUser` bigint(20) DEFAULT NULL,
  17.   PRIMARY KEY (`id`),
  18.   KEY `account_uid_user` (`uid`) USING BTREE,
  19.   KEY `account_createUser_user` (`createUser`) USING BTREE,
  20.   KEY `account_updateUser_user` (`updateUser`) USING BTREE,
  21.   CONSTRAINT `account_ibfk_1` FOREIGN KEY (`createUser`) REFERENCES `user` (`id`),
  22.   CONSTRAINT `account_ibfk_2` FOREIGN KEY (`uid`) REFERENCES `user` (`id`),
  23.   CONSTRAINT `account_ibfk_3` FOREIGN KEY (`updateUser`) REFERENCES `user` (`id`)
  24. ) ENGINE=InnoDB AUTO_INCREMENT=DEFAULT CHARSET=utf8;


  25. -- ----------------------------
  26. -- Table structure for `authority`角色菜单绑定表
  27. -- ----------------------------
  28. DROP TABLE IF EXISTS `authority`;
  29. CREATE TABLE `authority` (
  30.   `id` int(11) NOT NULL AUTO_INCREMENT,
  31.   `roleId` int(11) NOT NULL,
  32.   `sysmodelId` int(11) NOT NULL,
  33.   `remark` text,
  34.   `createTime` datetime DEFAULT NULL,
  35.   `createUser` int(11) DEFAULT NULL,
  36.   `updateTime` datetime DEFAULT NULL,
  37.   `updateUser` int(11) DEFAULT NULL,
  38.   PRIMARY KEY (`id`)
  39. ) ENGINE=InnoDB AUTO_INCREMENT=877 DEFAULT CHARSET=utf8;



  40. -- ----------------------------
  41. -- Table structure for `role`角色表
  42. -- ----------------------------
  43. DROP TABLE IF EXISTS `role`;
  44. CREATE TABLE `role` (
  45.   `id` int(11) NOT NULL AUTO_INCREMENT,
  46.   `roleName` varchar(200) NOT NULL,
  47.   `createTime` datetime DEFAULT NULL,
  48.   `createUser` int(11) DEFAULT NULL,
  49.   `updateTime` datetime DEFAULT NULL,
  50.   `updateUser` int(11) DEFAULT NULL,
  51.   `remark` text,
  52.   `isBenefit` smallint(6) DEFAULT NULL,
  53.   PRIMARY KEY (`id`)
  54. ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

  55. -- ----------------------------
  56. -- Records of role
  57. -- ----------------------------
  58. INSERT INTO `role` VALUES ('1', '经销商', null, null, '2013-05-08 11:25:55', null, '经销商备注', null);
  59. INSERT INTO `role` VALUES ('9', '管理员', null, null, '2013-05-08 11:25:59', null, '管理员权限', null);

  60. -- ----------------------------
  61. -- Table structure for `sysmodel`系统菜单表
  62. -- ----------------------------
  63. DROP TABLE IF EXISTS `sysmodel`;
  64. CREATE TABLE `sysmodel` (
  65.   `id` int(11) NOT NULL AUTO_INCREMENT,
  66.   `title` varchar(200) NOT NULL,
  67.   `modelName` varchar(200) NOT NULL,
  68.   `createTime` datetime DEFAULT NULL,
  69.   `createUser` int(11) DEFAULT NULL,
  70.   `updateTime` datetime DEFAULT NULL,
  71.   `updateUser` int(11) DEFAULT NULL,
  72.   PRIMARY KEY (`id`)
  73. ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

  74. -- ----------------------------
  75. -- Records of sysmodel
  76. -- ----------------------------
  77. INSERT INTO `sysmodel` VALUES ('1', '经销商管理', 'M01', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  78. INSERT INTO `sysmodel` VALUES ('2', '经销商入库', 'M0101', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  79. INSERT INTO `sysmodel` VALUES ('3', '经销商出库', 'M0102', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  80. INSERT INTO `sysmodel` VALUES ('4', '经销商分销', 'M0103', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  81. INSERT INTO `sysmodel` VALUES ('5', '经销商退货', 'M0104', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  82. INSERT INTO `sysmodel` VALUES ('6', '分销商管理', 'M02', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  83. INSERT INTO `sysmodel` VALUES ('7', '分销商入库', 'M0201', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  84. INSERT INTO `sysmodel` VALUES ('8', '分销商出库', 'M0202', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', '1');
  85. INSERT INTO `sysmodel` VALUES ('9', '分销商分销', 'M0203', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', null);
  86. INSERT INTO `sysmodel` VALUES ('10', '分销商退货', 'M0204', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', null);
  87. INSERT INTO `sysmodel` VALUES ('11', '管理员管理', 'M03', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', null);
  88. INSERT INTO `sysmodel` VALUES ('12', '角色管理', 'M04', '2011-12-02 00:00:00', '1', '2011-12-02 00:00:00', null);

  89. -- ----------------------------
  90. -- Table structure for `user`用户表
  91. -- ----------------------------
  92. DROP TABLE IF EXISTS `user`;
  93. CREATE TABLE `user` (
  94.   `id` bigint(20) NOT NULL AUTO_INCREMENT,
  95.   `badge` varchar(20) DEFAULT NULL,
  96.   `name` varchar(200) NOT NULL,
  97.   `ename` varchar(200) DEFAULT NULL,
  98.   `gender` varchar(5) DEFAULT NULL,
  99.   `company` varchar(200) DEFAULT NULL,
  100.   `department` varchar(200) DEFAULT NULL,
  101.   `job` varchar(200) DEFAULT NULL,
  102.   `idCardNo` varchar(20) DEFAULT NULL,
  103.   `birthday` date DEFAULT NULL,
  104.   `workYears` varchar(20) DEFAULT NULL,
  105.   `workLocation` varchar(200) DEFAULT NULL,
  106.   `email` varchar(200) DEFAULT NULL,
  107.   `mobile` varchar(20) DEFAULT NULL,
  108.   `createTime` datetime DEFAULT NULL,
  109.   `createUser` bigint(20) DEFAULT NULL,
  110.   `updateTime` datetime DEFAULT NULL,
  111.   `updateUser` bigint(20) DEFAULT NULL,
  112.   `roleId` int(11) DEFAULT NULL,
  113.   `status` varchar(10) NOT NULL DEFAULT 'on',
  114.   PRIMARY KEY (`id`),
  115.   KEY `createUser` (`createUser`) USING BTREE,
  116.   KEY `updateUser` (`updateUser`) USING BTREE,
  117.   CONSTRAINT `user_ibfk_1` FOREIGN KEY (`createUser`) REFERENCES `user` (`id`),
  118.   CONSTRAINT `user_ibfk_2` FOREIGN KEY (`updateUser`) REFERENCES `user` (`id`)
  119. ) ENGINE=InnoDB AUTO_INCREMENT=DEFAULT CHARSET=utf8;

3. 页面代码
注意:此处tree用到的dtree,基于javascript写的。而本人用过zTree后更推荐使用ztree,基于jquery的代码(功能点多,api详细)
因此必须先下载dtree,此处省略下载。
 
下载后将dtree自带的css和图片存放在项目制定路径下。

本人主要修改了dtree的js代码:实现checkbox,和异步访问功能

点击(此处)折叠或打开

  1. /*--------------------------------------------------|

  2. | dTree 2.05 | www.destroydrop.com/javascript/tree/ |

  3. |---------------------------------------------------|

  4. | Copyright (c) 2002-2003 Geir Landr? |

  5. | |

  6. | This script can be used freely as long as all |

  7. | copyright messages are intact. |

  8. | |

  9. | Updated: 17.04.2003 |

  10. |--------------------------------------------------*/



  11. // Node object

  12. function Node(id, pid, name, url, title, target, icon, iconOpen, open) {

  13.     this.id = id;

  14.     this.pid = pid;

  15.     this.name = name;

  16.     this.url = url;

  17.     this.title = title;

  18.     this.target = target;

  19.     this.icon = icon;

  20.     this.iconOpen = iconOpen;

  21.     this._io = open || false;

  22.     this._is = false;

  23.     this._ls = false;

  24.     this._hc = false;

  25.     this._ai = 0;

  26.     this._p;
  27.     //add by ljt
  28. //    this.checked=checked||false;

  29. };



  30. // Tree object

  31. function dTree(objName) {

  32.     this.config = {

  33.         target                    : null,
  34.        //ljt changed it to be false
  35.         folderLinks            : false,

  36.         useSelection        : true,

  37.         useCookies            : true,

  38.         useLines                : true,

  39.         useIcons                : true,

  40.         useStatusText        : false,

  41.         closeSameLevel    : false,

  42.         inOrder    : false,
  43.         
  44.         check: true //添加选择框

  45.     }
  46.  //ljt changed this to his own path 
  47.     this.icon = {

  48.         //root                : '../images/dtree/base.gif',
  49.      root                : '../images/dtree/ware.png',

  50.         //folder            : '../images/dtree/folder.gif',
  51.      folder                : '../images/dtree/note.png',

  52.         //folderOpen        : '../images/dtree/folderopen.gif',
  53.      folderOpen            : '../images/dtree/note.png',

  54.         //node                : '../images/dtree/page.gif',
  55.      node                : '../images/dtree/note.png',

  56.         empty                : '../images/dtree/empty.gif',

  57.         line                : '../images/dtree/line.gif',

  58.         join                : '../images/dtree/join.gif',

  59.         joinBottom    : '../images/dtree/joinbottom.gif',

  60.         plus                : '../images/dtree/plus.gif',

  61.         plusBottom    : '../images/dtree/plusbottom.gif',

  62.         minus                : '../images/dtree/minus.gif',

  63.         minusBottom    : '../images/dtree/minusbottom.gif',

  64.         nlPlus            : '../images/dtree/nolines_plus.gif',

  65.         nlMinus            : '../images/dtree/nolines_minus.gif'

  66.     };
  67.     //add by ljt
  68.     this.cbCollection=new Object();
  69.     
  70.     
  71.     this.obj = objName;

  72.     this.aNodes = [];
  73.     
  74.     this.aIndent = [];

  75.     this.root = new Node(-1);

  76.     this.selectedNode = null;

  77.     this.selectedFound = false;

  78.     this.completed = false;

  79. };


  80. // Adds a new node to the node array

  81. dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open) {
  82.  
  83.     this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open);

  84. };

  85. // Open/close all nodes

  86. dTree.prototype.openAll = function() {

  87.     this.oAll(true);

  88. };

  89. dTree.prototype.closeAll = function() {

  90.     this.oAll(false);

  91. };



  92. // Outputs the tree to the page

  93. dTree.prototype.toString = function() {

  94.     var str = '<div class="dtree">n';

  95.     if (document.getElementById) {

  96.         if (this.config.useCookies) this.selectedNode = this.getSelected();

  97.         str += this.addNode(this.root);

  98.     } else str += 'Browser not supported.';

  99.     str += '</div>';

  100.     if (!this.selectedFound) this.selectedNode = null;

  101.     this.completed = true;
  102.     
  103.     return str;

  104. };



  105. // Creates the tree structure

  106. dTree.prototype.addNode = function(pNode) {

  107.     var str = '';

  108.     var n=0;

  109.     if (this.config.inOrder) n = pNode._ai;

  110.     for (n; n<this.aNodes.length; n++) {

  111.         if (this.aNodes[n].pid == pNode.id) {

  112.             var cn = this.aNodes[n];

  113.             cn._p = pNode;

  114.             cn._ai = n;

  115.             this.setCS(cn);

  116.             if (!cn.target && this.config.target) cn.target = this.config.target;

  117.             if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id);

  118.             if (!this.config.folderLinks && cn._hc) cn.url = null;

  119.             if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {

  120.                     cn._is = true;

  121.                     this.selectedNode = n;

  122.                     this.selectedFound = true;

  123.             }

  124.             str += this.node(cn, n);

  125.             if (cn._ls) break;

  126.         }

  127.     }

  128.     return str;

  129. };
  130. //设置某节点不可选
  131. dTree.prototype.unSelected=function(nodeId){
  132.     var ids=document.getElementsByName("c"+this.obj+"_Id");
  133.     var tempIds=nodeId.split(",");
  134.     for(var n=1;n<tempIds.length;n++){
  135.         for(var i=0;i<ids.length;i++){
  136.             if("c"+this.obj+tempIds[n]==ids[i].id){
  137.                 ids[i].disabled=true;
  138.                 break;
  139.             }
  140.         }
  141.     }
  142. }
  143. //add by ljt set Default checked
  144. dTree.prototype.defaultChecked=function(nodeId){
  145. //    var checkbox_nameId="c"+this.obj+"_Id";
  146.     var ids = document.getElementsByName("c"+this.obj+"_Id");
  147.     var tempIds=nodeId.split(",");
  148.     for(var n=0; n < tempIds.length; n++){
  149.      for(var i=0; i<ids.length; i++){
  150.             if("c"+this.obj+tempIds[n] == ids[i].id){
  151.              ids[i].checked=true;
  152.              break;
  153.             }
  154.         }
  155.     }
  156.      
  157. };

  158. //add by ljt 
  159. dTree.prototype.co=function(id){ 
  160.     if (this.cbCollection[id])return this.cbCollection[id]; 
  161.     for(var n=0; n<this.aNodes.length; n++){ 
  162.         if(this.aNodes[n].id==id){ 
  163.            this.cbCollection[id]=document.getElementById("c"+this.obj+id); 
  164.             break; 
  165.         } 
  166.     } 
  167.     return this.cbCollection[id]; 
  168. }; 

  169. //获取选择的节点
  170. dTree.prototype.getText=function(){
  171.      var value=new Array();
  172.      var cko;//checkobject
  173.      
  174.          for(var n=0;n<this.aNodes.length;n++){
  175.      cko=this.co(this.aNodes[n].id);
  176.      if(cko!=null){
  177.      if(cko.checked==true){
  178.              value[value.length]=this.aNodes[n].id;
  179.             }
  180.      }
  181.      }
  182.      return value;
  183.      
  184. };



  185. // Creates the node icon, url and text

  186. dTree.prototype.node = function(node, nodeId) {

  187.     var str = '<div class="dTreeNode">' + this.indent(node, nodeId);

  188.     if (this.config.useIcons) {

  189.         if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);

  190.         if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;

  191.         if (this.root.id == node.pid) {

  192.             node.icon = this.icon.root;

  193.             node.iconOpen = this.icon.root;

  194.         }

  195.         str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
  196.         
  197.         //添加输出的复选框
  198.         if(this.config.check==true){
  199.          str+='<input type="checkbox" name="c'+this.obj+'_Id" id="c'+this.obj+node.id+'" onclick="javascript:'+this.obj+'.cc(''+node.id+'',''+node.pid+'')"/>';
  200.         }

  201.     }
  202.     //复选框
  203.     dTree.prototype.cc=function(nodeId, nodePid){
  204.      
  205.     //首先获取这个复选框的id
  206.      var cs = document.getElementById("c" + this.obj + nodeId).checked;
  207.      
  208.     var n,node = this.aNodes[nodeId];
  209.      
  210.     var len = this.aNodes.length;
  211.      
  212.     for (n=0; n<len; n++) { //循环每一个节点
  213.         if (this.aNodes[n].pid == nodeId) { //选择的是非子节点,则要把父节点和子节点全部选中
  214.             document.getElementById("c" + this.obj + this.aNodes[n].id).checked = cs; 
  215.             this.cc(this.aNodes[n].id, nodeId); //循环节点 
  216.         } 
  217.     } 
  218.     
  219.      if(cs==true){ //节点被选中状态
  220.         var pid=nodePid; 
  221.         var bSearch; 
  222.         do{ 
  223.             bSearch=false; 
  224.             for(n=0;n<len;n++){ //循环每一个节点
  225.                 if(this.aNodes[n].id==pid){ //如果循环的节点的Id等于PId
  226.                      document.getElementById("c"+this.obj+pid).checked=true; //那么这个循环的节点应该被选中
  227.                     pid=this.aNodes[n].pid; 
  228.                     bSearch= true; 
  229.                     break; 
  230.                 } 
  231.             } 
  232.         }while(bSearch==true);
  233.        }
  234.        
  235.       if(cs==false){ //取消选择
  236.         var pid = nodePid; 
  237.         do{ 
  238.             for(j=0;j<len;j++){ //循环每一个多选框,如果该节点有其他子节点被选中,则不取消
  239.                 if(this.aNodes[j].pid==pid && document.getElementById("c" + this.obj + this.aNodes[j].id).checked==true){ 
  240.                     return; 
  241.                 } 
  242.             } 
  243.             if(j==len){ //循环结束
  244.                 for(k=0;k<len;k++){ 
  245.                     if(this.aNodes[k].id==pid){ //找到父节点
  246.                         document.getElementById("c"+this.obj+this.aNodes[k].id).checked=false; 
  247.                         pid=this.aNodes[k].pid; 
  248.                         break; 
  249.                     } 
  250.                 } 
  251.             } 
  252.         }while(pid!=-1); 
  253.     }
  254.  }


  255.     if (node.url) {

  256.         str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + '" href="' + node.url + '"';

  257.         if (node.title) str += ' title="' + node.title + '"';

  258.         if (node.target) str += ' target="' + node.target + '"';

  259.         if (this.config.useStatusText) str += ' onmouseover="window.status='' + node.name + '';return true;" onmouseout="window.status='';return true;" ';

  260.         if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))

  261.             str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"';

  262.         str += '>';

  263.     }

  264.     else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)

  265.         str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';

  266.     str += node.name;

  267.     if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>';

  268.     str += '</div>';

  269.     if (node._hc) {

  270.         str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';

  271.         str += this.addNode(node);

  272.         str += '</div>';

  273.     }

  274.     this.aIndent.pop();

  275.     return str;

  276. };



  277. // Adds the empty and line icons

  278. dTree.prototype.indent = function(node, nodeId) {

  279.     var str = '';

  280.     if (this.root.id != node.pid) {

  281.         for (var n=0; n<this.aIndent.length; n++)

  282.             str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';

  283.         (node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);

  284.         if (node._hc) {

  285.             str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';

  286.             if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;

  287.             else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );

  288.             str += '" alt="" /></a>';

  289.         } else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';

  290.     }

  291.     return str;

  292. };



  293. // Checks if a node has any children and if it is the last sibling

  294. dTree.prototype.setCS = function(node) {

  295.     var lastId;

  296.     for (var n=0; n<this.aNodes.length; n++) {

  297.         if (this.aNodes[n].pid == node.id) node._hc = true;

  298.         if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;

  299.     }

  300.     if (lastId==node.id) node._ls = true;

  301. };



  302. // Returns the selected node

  303. dTree.prototype.getSelected = function() {

  304.     var sn = this.getCookie('cs' + this.obj);

  305.     return (sn) ? sn : null;

  306. };



  307. // Highlights the selected node

  308. dTree.prototype.= function(id) {

  309.     if (!this.config.useSelection) return;

  310.     var cn = this.aNodes[id];

  311.     if (cn._hc && !this.config.folderLinks) return;

  312.     if (this.selectedNode != id) {

  313.         if (this.selectedNode || this.selectedNode==0) {

  314.             eOld = document.getElementById("s" + this.obj + this.selectedNode);

  315.             eOld.className = "node";

  316.         }

  317.         eNew = document.getElementById("s" + this.obj + id);

  318.         eNew.className = "nodeSel";

  319.         this.selectedNode = id;

  320.         if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id);

  321.     }

  322. };



  323. // Toggle Open or close

  324. dTree.prototype.= function(id) {

  325.     var cn = this.aNodes[id];

  326.     this.nodeStatus(!cn._io, id, cn._ls);

  327.     cn._io = !cn._io;

  328.     if (this.config.closeSameLevel) this.closeLevel(cn);

  329.     if (this.config.useCookies) this.updateCookie();

  330. };



  331. // Open or close all nodes

  332. dTree.prototype.oAll = function(status) {

  333.     for (var n=0; n<this.aNodes.length; n++) {

  334.         if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {

  335.             this.nodeStatus(status, n, this.aNodes[n]._ls)

  336.             this.aNodes[n]._io = status;

  337.         }

  338.     }

  339.     if (this.config.useCookies) this.updateCookie();

  340. };



  341. // Opens the tree to a specific node

  342. dTree.prototype.openTo = function(nId, bSelect, bFirst) {

  343.     if (!bFirst) {

  344.         for (var n=0; n<this.aNodes.length; n++) {

  345.             if (this.aNodes[n].id == nId) {

  346.                 nId=n;

  347.                 break;

  348.             }

  349.         }

  350.     }

  351.     var cn=this.aNodes[nId];

  352.     if (cn.pid==this.root.id || !cn._p) return;

  353.     cn._io = true;

  354.     cn._is = bSelect;

  355.     if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls);

  356.     if (this.completed && bSelect) this.s(cn._ai);

  357.     else if (bSelect) this._sn=cn._ai;

  358.     this.openTo(cn._p._ai, false, true);

  359. };



  360. // Closes all nodes on the same level as certain node

  361. dTree.prototype.closeLevel = function(node) {

  362.     for (var n=0; n<this.aNodes.length; n++) {

  363.         if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {

  364.             this.nodeStatus(false, n, this.aNodes[n]._ls);

  365.             this.aNodes[n]._io = false;

  366.             this.closeAllChildren(this.aNodes[n]);

  367.         }

  368.     }

  369. }



  370. // Closes all children of a node

  371. dTree.prototype.closeAllChildren = function(node) {

  372.     for (var n=0; n<this.aNodes.length; n++) {

  373.         if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {

  374.             if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);

  375.             this.aNodes[n]._io = false;

  376.             this.closeAllChildren(this.aNodes[n]);        

  377.         }

  378.     }

  379. }



  380. // Change the status of a node(open or closed)

  381. dTree.prototype.nodeStatus = function(status, id, bottom) {

  382.     eDiv    = document.getElementById('d' + this.obj + id);

  383.     eJoin    = document.getElementById('j' + this.obj + id);

  384.     if (this.config.useIcons) {

  385.         eIcon    = document.getElementById('i' + this.obj + id);

  386.         eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;

  387.     }

  388.     eJoin.src = (this.config.useLines)?

  389.     ((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)):

  390.     ((status)?this.icon.nlMinus:this.icon.nlPlus);

  391.     eDiv.style.display = (status) ? 'block': 'none';

  392. };





  393. // [Cookie] Clears a cookie

  394. dTree.prototype.clearCookie = function() {

  395.     var now = new Date();

  396.     var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);

  397.     this.setCookie('co'+this.obj, 'cookieValue', yesterday);

  398.     this.setCookie('cs'+this.obj, 'cookieValue', yesterday);

  399. };



  400. // [Cookie] Sets value in a cookie

  401. dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {

  402.     document.cookie =

  403.         escape(cookieName) + '=' + escape(cookieValue)

  404.         + (expires ? '; expires=' + expires.toGMTString() : '')

  405.         + (path ? '; path=' + path : '')

  406.         + (domain ? '; domain=' + domain : '')

  407.         + (secure ? '; secure' : '');

  408. };



  409. // [Cookie] Gets a value from a cookie

  410. dTree.prototype.getCookie = function(cookieName) {

  411.     var cookieValue = '';

  412.     var posName = document.cookie.indexOf(escape(cookieName) + '=');

  413.     if (posName != -1) {

  414.         var posValue = posName + (escape(cookieName) + '=').length;

  415.         var endPos = document.cookie.indexOf(';', posValue);

  416.         if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));

  417.         else cookieValue = unescape(document.cookie.substring(posValue));

  418.     }

  419.     return (cookieValue);

  420. };



  421. // [Cookie] Returns ids of open nodes as a string

  422. dTree.prototype.updateCookie = function() {

  423.     var str = '';

  424.     for (var n=0; n<this.aNodes.length; n++) {

  425.         if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {

  426.             if (str) str += '.';

  427.             str += this.aNodes[n].id;

  428.         }

  429.     }

  430.     this.setCookie('co' + this.obj, str);

  431. };



  432. // [Cookie] Checks if a node id is in a cookie

  433. dTree.prototype.isOpen = function(id) {

  434.     var aOpen = this.getCookie('co' + this.obj).split('.');

  435.     for (var n=0; n<aOpen.length; n++)

  436.         if (aOpen[n] == id) return true;

  437.     return false;

  438. };



  439. // If Push and pop is not implemented by the browser

  440. if (!Array.prototype.push) {

  441.     Array.prototype.push = function array_push() {

  442.         for(var i=0;i<arguments.length;i++)

  443.             this[this.length]=arguments[i];

  444.         return this.length;

  445.     }

  446. };

  447. if (!Array.prototype.pop) {

  448.     Array.prototype.pop = function array_pop() {

  449.         lastElement = this[this.length-1];

  450.         this.length = Math.max(this.length-1,0);

  451.         return lastElement;

  452.     }

  453. };



jsp:代码
RoleManagerEdit.jsp

点击(此处)折叠或打开

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <%@ page contentType="text/html; charset=UTF-8"%>
  3. <%@ taglib prefix="s" uri="/struts-tags"%>

  4. <html>
  5. <head><title></title>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  7. <% String path=request.getContextPath();
  8.    String objId = (String)request.getAttribute("objId");
  9.    %>

  10. <link rel="stylesheet" type="text/css" href="<%=path%>/css/jquery-ui-1.8.23.custom.css" />
  11. <link rel="stylesheet" type="text/css" href="<%=path%>/css/dtree.css" />

  12. <script type=text/javascript src="<%=path%>/js/common/jquery-1.7.2.js"></script>
  13. <script type=text/javascript src="<%=path%>/js/common/jquery-ui-1.8.23.custom.min.js"></script>
  14. <script type=text/javascript src="<%=path%>/js/common/jquery.ui.datepicker-zh-CN.js"></script>
  15. <script type=text/javascript src="<%=path%>/js/common/dateUtil.js"></script>
  16. <script type=text/javascript src="<%=path%>/js/common/page.js"></script>
  17. <script type=text/javascript src="<%=path%>/js/dynamic.jsp"></script>
  18. <script type="text/javascript" src="<%=path%>/js/dtree.js"></script>
  19. <script type="text/javascript" src="<%=path%>/js/authorityTree.js"></script>
  20. <script type="text/javascript">
  21. var tree = new dTree("tree");
  22. /* function doSave(p, url) {
  23.     var array = p.getText();
  24.     $("#authority").val(array);
  25.     $('form')[0].action=url;
  26.     $('form')[0].submit();
  27. } */
  28. function doSave(p, url) {
  29.     var array = p.getText();
  30.     $("#authority").val(array);
  31.     
  32.     var msg = "";
  33.     var roleName = $('#roleName');
  34.     if(roleName.val()==''){
  35.         if(msg!="")
  36.         {
  37.             msg+="、请填写角色名称";
  38.         }else{
  39.             msg +="请填写角色名称";
  40.         }
  41.         roleName.addClass("terror"); 
  42.     }
  43.     if(msg!="") {
  44.          $("#messageDivId").html(msg);
  45.          window.scrollTo(0);//置顶
  46.          return false;
  47.     }else{
  48.          if(confirm("确认 提交?")){
  49.              $('form')[0].action=url;
  50.              $('form')[0].submit();
  51.          }
  52.         
  53.        }
  54. }
  55. $(document).ready(function () {
  56.     var author = $("#authority").val();
  57.     authority($("#tree"), tree, author);

  58. });
  59. function goback(url){
  60.     $('form')[0].action=url;
  61.     $('form')[0].submit();
  62. }
  63. </script>
  64. </head>
  65. <body>
  66. <form action="" method="post" name="_testForm" id="form" >
  67. <s:token />
  68.  <input type="hidden" name="detailBean.authority" id="authority" value=".authority"/>"/>
  69.   <input type="hidden" name="detailBean.id" id="deId" value=".id"/>"/>
  70. <div id="main">
  71. <jsp:include page="head.jsp" />
  72.         <div id="middle">
  73.         <jsp:include page="leftMenu.jsp" />
  74.          <div class="left_middle"> 
  75.             <p>当前位置:<span id="position_span"></span></p>
  76.               <h2>角色信息</h2> 
  77.            <div id="messageDivId"></div>
  78.               <ul> 
  79.               <table width="100%" cellspacing="0" border="0" style="padding-left: 25px"> 
  80.               <tbody>
  81.               <tr>
  82.               <td width="70px">角色名称:</td>
  83.               <td><s:textfield name="detailBean.roleName" id="roleName"/>&nbsp;<font color="red">*</font></td> 
  84.                </tr>
  85.               <tr>
  86.                <td width="70px">角色描述:</td>
  87.               <td><s:textarea cols="95" rows="4" name="detailBean.remark" cssStyle="width:70%;" cssClass="toff" onchange="this.className='toff'" /> </td> 
  88.                 </tr>
  89.               </tbody> 
  90.             </table> 
  91.              <h4>权限分配</h4>
  92.         <div class="dtree">
  93.           <p><a href="javascript: tree.openAll();">全部展开</a> | <a href="javascript: tree.closeAll();">全部收拢</a></p>
  94.           <div id="tree">
  95.           </div> 
  96.         </div>
  97.         <div style="padding-top: 20px">
  98.          <input type="button" name="save" class="button1" value="提交" onclick="doSave(tree,'<%=path%>/role/roleManagerupdate.do')" />
  99.            <input type="button" name="back" class="button1" value="返回" onclick="goback('<%=path%>/role/roleManagerlist.do')">
  100.           
  101.         </div>
  102.             
  103.       </div>
  104.         <div style="clear:both"></div>
  105.     </div>
  106.   </div>
  107.    <script type="text/javascript">switchLeftMenu(17);</script>
  108.   <jsp:include page="footer.jsp"></jsp:include>
  109. </form>
  110. </body>
  111. </html>


自定义权限标签:expand.tld

点击(此处)折叠或打开

  1. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  3. version="2.0">
  4. Schedule Tag Library
  5. 1.0
  6. expand
  7. /expand
  8. ifauthorize
  9. com.easytalent.common.tag.PermissionTag
  10. JSP
  11. author
  12. true
  13. true
  14. notauthorize
  15. com.easytalent.common.tag.NoPermissionTag
  16. JSP
  17. author
  18. true
  19. true

后端java代码待整理

Action层代码:

点击(此处)折叠或打开

  1. package com.easytalent.manager.action;

  2. import java.util.List;

  3. import net.sf.json.JSONArray;
  4. import net.sf.json.JSONObject;

  5. import org.hibernate.annotations.common.util.StringHelper;
  6. import org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException;

  7. import com.easytalent.base.action.BaseAction;
  8. import com.easytalent.manager.bean.RoleBean;
  9. import com.easytalent.manager.task.RoleManagerTask;
  10. import com.easytalent.storage.model.Role;
  11. import com.easytalent.storage.model.Sysmodel;
  12. import com.easytalent.util.Page;
  13. import com.easytalent.util.StackTraceUtil;

  14. public class RoleManagerAction extends BaseAction {

  15.     private RoleManagerTask roleManagerTask;//角色管理task
  16.     private List<Role> roleList;//角色list
  17.     private RoleBean detailBean=new RoleBean();//详细bean
  18.     private RoleBean searchBean;//查询bean
  19.     private Page page =new Page();
  20.     
  21.     
  22.     
  23.     public Page getPage() {
  24.         return page;
  25.     }
  26.     public void setPage(Page page) {
  27.         this.page = page;
  28.     }
  29.     public RoleManagerTask getRoleManagerTask() {
  30.         return roleManagerTask;
  31.     }
  32.     public void setRoleManagerTask(RoleManagerTask roleManagerTask) {
  33.         this.roleManagerTask = roleManagerTask;
  34.     }
  35.     public List<Role> getRoleList() {
  36.         return roleList;
  37.     }
  38.     public void setRoleList(List<Role> roleList) {
  39.         this.roleList = roleList;
  40.     }
  41.     public RoleBean getDetailBean() {
  42.         return detailBean;
  43.     }
  44.     public void setDetailBean(RoleBean detailBean) {
  45.         this.detailBean = detailBean;
  46.     }
  47.     public RoleBean getSearchBean() {
  48.         return searchBean;
  49.     }
  50.     public void setSearchBean(RoleBean searchBean) {
  51.         this.searchBean = searchBean;
  52.     }
  53.     /**
  54.      * 角色管理action
  55.      * @return
  56.      */
  57.     public String list() {
  58.         try {
  59.             this.initBase();
  60.             roleList = roleManagerTask.getAll(searchBean,page);
  61.             this.page.setPagebar();
  62.             return LIST;
  63.         } catch (Exception e) {
  64.             logger.error(StackTraceUtil.getStackTrace(e));
  65.         } finally {
  66.         }
  67.         return ERROR;
  68.     }
  69.     /**
  70.      * 角色管理新增空跳转
  71.      * @return
  72.      */
  73.     public String add() {
  74.         try {
  75.             this.initBase(); // 初始化
  76.             StringBuilder sb = new StringBuilder("");
  77.             String objId = utilBean.getObjId();
  78.             return EDIT;
  79.         } catch (HibernateObjectRetrievalFailureException e) {
  80.             // 如果关联到了脏数据,会抛出磁异常(数据库没设外间,有可能有脏数据在里面)
  81.         } catch (Exception e) {
  82.         } finally {
  83.         }
  84.         return ERROR;
  85.     }
  86.     /**
  87.      * 获得菜单树
  88.      * 
  89.      * @return
  90.      */
  91.     public String tree() {
  92.         try {
  93.             this.initBase(); // 初始化
  94.             List<Sysmodel> list = roleManagerTask.getAuthorityTree();
  95.             JSONArray jsonArray = new JSONArray();
  96.            JSONObject json = null;
  97.             for (Sysmodel model : list) {
  98.                 json = new JSONObject();
  99.                 json.put("id", model.getId());
  100.                 json.put("name", model.getModelName());
  101.                 json.put("title", model.getTitle());
  102.                 jsonArray.add(json);
  103.             }
  104.             json=new JSONObject();
  105.            json.put("success", true);
  106.            json.put("data", jsonArray);
  107.            this.outPrint(json);
  108.             return NONE;
  109.         } catch (HibernateObjectRetrievalFailureException e) {
  110.             // 如果关联到了脏数据,会抛出磁异常(数据库没设外间,有可能有脏数据在里面)
  111.         } catch (Exception e) {
  112.         } finally {
  113.         }
  114.         return ERROR;
  115.     }
  116.     /**
  117.      * 查看方法
  118.      * @return
  119.      */
  120.     public String detail() {
  121.         try {
  122.             this.initBase();// 初始化
  123.             String objId = this.utilBean.getObjId();
  124.             StringBuilder sb = new StringBuilder("");
  125.             if (StringHelper.isNotEmpty(objId)) {
  126.                 Role model = roleManagerTask.findById(Long.valueOf(objId));
  127.                 this.detailBean = roleManagerTask.model2detailBean(model);
  128.                 List<String> authors = roleManagerTask.getAuthors(Long.valueOf(objId));
  129.                 if (authors != null) {
  130.                     for (String author : authors) {
  131.                         sb.append(",");
  132.                         sb.append(author);
  133.                     }
  134.                 }
  135.                 if (sb.length() > 0) {
  136.                     detailBean.setAuthority(sb.substring(1));
  137.                     detailBean.setId(Long.valueOf(objId));
  138.                 } else {
  139.                     detailBean.setAuthority("");
  140.                     detailBean.setId(Long.valueOf(objId));
  141.                 }
  142.                 return DETAIL;
  143.             }
  144.         } catch (NumberFormatException e) {
  145.             // TODO Auto-generated catch block
  146.             e.printStackTrace();
  147.         } catch (Exception e) {
  148.             // TODO Auto-generated catch block
  149.             e.printStackTrace();
  150.         }
  151.         return LIST;
  152.     }
  153.     /**
  154.      * 修改新增方法
  155.      * @return
  156.      */
  157.     public String update() {
  158.         try {
  159.             this.initBase();// 初始化
  160.             Long objId = this.detailBean.getId();
  161.             if (request.getParameter("struts.token").equals( 
  162.                     request.getSession().getAttribute("struts.token"))) {
  163.                 if (objId!=null) {// 修改
  164.                     Role model = roleManagerTask.detail2model(detailBean);
  165.                     model = roleManagerTask.updateRole(model);
  166.                     roleManagerTask.saveAuthority(model.getId(), detailBean.getAuthority());//先删掉之前的在新增现在的
  167.                     this.utilBean.setMessage(this.getText("msg.update.success"));
  168.                 } else {// 新增
  169.                     Role model = roleManagerTask.detail2model(detailBean);
  170.                     model = roleManagerTask.saveRole(model);
  171.                     roleManagerTask.saveAuthority(model.getId(), detailBean.getAuthority());
  172.                     this.utilBean.setMessage(this.getText("msg.submit.success"));
  173.                 }
  174.             }
  175.             return list();// 一览页面
  176.         } catch (Exception e) {
  177.         } finally {
  178.         }
  179.         return ERROR;
  180.     }
  181. }

Task业务层:

点击(此处)折叠或打开

  1. package com.easytalent.manager.task.impl;

  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.List;

  5. import org.springframework.beans.BeanUtils;

  6. import com.easytalent.manager.bean.RoleBean;
  7. import com.easytalent.manager.task.RoleManagerTask;
  8. import com.easytalent.storage.dao.AccountDao;
  9. import com.easytalent.storage.dao.AuthorityDao;
  10. import com.easytalent.storage.dao.RoleManagerDao;
  11. import com.easytalent.storage.dao.SysmodelDao;
  12. import com.easytalent.storage.model.Account;
  13. import com.easytalent.storage.model.Authority;
  14. import com.easytalent.storage.model.Role;
  15. import com.easytalent.storage.model.Sysmodel;
  16. import com.easytalent.util.ComUtil;
  17. import com.easytalent.util.Page;

  18. public class RoleManagerTaskImpl implements RoleManagerTask {

  19.     private RoleManagerDao roleManagerDao;// 角色管理dao
  20.     private AccountDao accountDao;
  21.     private AuthorityDao authorityDao;// 角色权限表
  22.     private SysmodelDao sysmodelDao;// 系统菜单表

  23.     public SysmodelDao getSysmodelDao() {
  24.         return sysmodelDao;
  25.     }

  26.     public void setSysmodelDao(SysmodelDao sysmodelDao) {
  27.         this.sysmodelDao = sysmodelDao;
  28.     }

  29.     public AuthorityDao getAuthorityDao() {
  30.         return authorityDao;
  31.     }

  32.     public void setAuthorityDao(AuthorityDao authorityDao) {
  33.         this.authorityDao = authorityDao;
  34.     }

  35.     public AccountDao getAccountDao() {
  36.         return accountDao;
  37.     }

  38.     public void setAccountDao(AccountDao accountDao) {
  39.         this.accountDao = accountDao;
  40.     }

  41.     public RoleManagerDao getRoleManagerDao() {
  42.         return roleManagerDao;
  43.     }

  44.     public void setRoleManagerDao(RoleManagerDao roleManagerDao) {
  45.         this.roleManagerDao = roleManagerDao;
  46.     }

  47.     public List<Role> getAll(RoleBean bean, Page page) throws Exception {
  48.         try {
  49.             if (page.getOrderBy() == null || "".equals(page.getOrderBy())) {
  50.                 page.setOrderBy("o.updateTime desc");
  51.             }
  52.             List<Role> list = roleManagerDao.getAllRolses(bean, page);
  53.             return list;
  54.         } catch (Exception e) {
  55.             // logger.error(StackTraceUtil.getStackTrace(e));
  56.             throw e;
  57.         } finally {
  58.         }
  59.     }

  60.     public Role saveRole(Role model) throws Exception {
  61.         try {
  62.             model = roleManagerDao.save(model);
  63.             return model;
  64.         } catch (Exception e) {
  65.             // logger.error(StackTraceUtil.getStackTrace(e));
  66.             throw e;
  67.         } finally {
  68.         }
  69.     }

  70.     @Override
  71.     public Role detail2model(RoleBean detailBean) {
  72.         Role modelBean = null;
  73.         if (detailBean != null) {
  74.             modelBean = new Role();
  75.             BeanUtils.copyProperties(detailBean, modelBean);
  76.         }
  77.         return modelBean;
  78.     }

  79.     @Override
  80.     public RoleBean model2detailBean(Role model) {
  81.         RoleBean detailBean = null;
  82.         if (model != null) {
  83.             detailBean = new RoleBean();
  84.             BeanUtils.copyProperties(model, detailBean);

  85.         }
  86.         return detailBean;
  87.     }

  88.     @Override
  89.     public Role findById(Long objId) throws Exception {
  90.         try {
  91.             return roleManagerDao.get(objId);
  92.         } catch (Exception e) {
  93.             // logger.error(StackTraceUtil.getStackTrace(e));
  94.             throw e;
  95.         } finally {
  96.         }
  97.     }

  98.     @Override
  99.     public Account getUserInfo(String id) throws Exception {
  100.         try {
  101.             return accountDao.get(Long.valueOf(id));
  102.         } catch (Exception e) {
  103.             // logger.error(StackTraceUtil.getStackTrace(e));
  104.             throw e;
  105.         } finally {
  106.         }
  107.     }

  108.     @Override
  109.     public List<String> getAuthors(Long roleId) {
  110.         List<String> authors = authorityDao.getByRoleId(roleId);
  111.         if (authors == null) {
  112.             return null;
  113.         }
  114.         List<String> authority = new ArrayList<String>();
  115.         for (String author : authors) {
  116.             authority.add(author);
  117.         }
  118.         return authority;
  119.     }

  120.     @Override
  121.     public List<Sysmodel> getAuthorityTree() throws Exception {
  122.         try {
  123.             List<Sysmodel> list = sysmodelDao.getAuthorityList();
  124.             return list;
  125.         } catch (Exception e) {
  126.             // logger.error(StackTraceUtil.getStackTrace(e));
  127.             throw e;
  128.         } finally {
  129.         }
  130.     }

  131.     public String saveAuthority(Long roleId, String authorlist)
  132.             throws Exception {
  133.         authorityDao.deleteAuthority(roleId);// 清空此角色的权限
  134.         if (authorlist == null) {
  135.             return "";
  136.         }
  137.         Authority authority = null;
  138.         for (String author : authorlist.split(",", -1)) {
  139.             authority = new Authority();
  140.             Sysmodel sysmodel = sysmodelDao.getSysmodel(author);
  141.             if (sysmodel == null) {
  142.                 continue;
  143.             }
  144.             authority.setRoleId(roleId);
  145.             authority.setSysmodel(sysmodel);
  146.             authority.setCreateTime(new Date());
  147.             authority.setUpdateTime(new Date());
  148.             this.authorityDao.save(authority);
  149.         }
  150.         return authorlist;

  151.     }

  152.     @Override
  153.     public Role updateRole(Role model) throws Exception {
  154.         Date nowDate = ComUtil.getSystemDate();
  155.         model.setUpdateTime(nowDate);
  156.         return roleManagerDao.update(model);
  157.     }

  158. }

DAO层:

点击(此处)折叠或打开

  1. RoleManagerDaoImpl

  2. package com.easytalent.storage.dao.impl;

  3. import java.util.ArrayList;
  4. import java.util.List;

  5. import org.hibernate.annotations.common.util.StringHelper;

  6. import java.util.List;

  7. import com.easytalent.base.dao.impl.GenericDaoImpl;
  8. import com.easytalent.manager.bean.RoleBean;
  9. import com.easytalent.storage.dao.RoleManagerDao;
  10. import com.easytalent.storage.model.Role;
  11. import com.easytalent.util.Page;

  12. public class RoleManagerDaoImpl extends GenericDaoImpl<Role, Long> implements
  13.         RoleManagerDao {
  14.     public RoleManagerDaoImpl() {
  15.         super(Role.class);
  16.     }
  17.     /**
  18.        * 取得学位List
  19.        */
  20.       public List<Role> getRoleList() {
  21.           String hql = "from Role c order by c.id asc";
  22.           return this.findByHql(hql);
  23.       }
  24.     @Override
  25.     public List<Role> getAllRolses(RoleBean bean, Page page) {
  26.         Object[] paramArray = null;
  27.         StringBuilder hql = new StringBuilder();
  28.         hql.append("from Role o where 1=1 ");
  29.         if (bean != null) {
  30.             List<Object> param = new ArrayList<Object>();
  31.             String name = bean.getRoleName();
  32.             if (StringHelper.isNotEmpty(name)) {
  33.                 hql.append("and o.roleName like ? ");
  34.                 param.add("%" + name.trim() + "%");
  35.             }
  36.             paramArray = param.toArray();
  37.         }
  38.         hql.append(" order by ");
  39.         hql.append(page.getOrderBy());
  40.         return this.findByHql(hql.toString(), paramArray, page);
  41.     }

  42. }


点击(此处)折叠或打开

  1. package com.easytalent.storage.dao.impl;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. import com.easytalent.base.dao.impl.GenericDaoImpl;
  5. import com.easytalent.storage.dao.SysmodelDao;
  6. import com.easytalent.storage.model.Sysmodel;

  7. public class SysmodelDaoImpl extends GenericDaoImpl<Sysmodel, Long> implements
  8.         SysmodelDao {
  9.     public SysmodelDaoImpl() {
  10.         super(Sysmodel.class);
  11.     }

  12.     @Override
  13.     public List<Sysmodel> getAuthorityList() {
  14.         String hql = "from Sysmodel t order by t.modelName asc ";
  15.         return this.findByHql(hql);
  16.     }
  17.      /**
  18.      * 通过名称取得菜单模型
  19.      * @return
  20.      */
  21.     public Sysmodel getSysmodel(String modelName) {
  22.         Object[] paramArray = null;
  23.         List<Object> param = new ArrayList<Object>();
  24.         String hql = "from Sysmodel t where t.modelName = ? ";
  25.         param.add(modelName);
  26.         paramArray = param.toArray();
  27.         Object obj = this.findUniqueResult(hql, paramArray);
  28.         if (obj != null) {
  29.             return (Sysmodel) obj;
  30.         }
  31.         return null;
  32.     }
  33. }


点击(此处)折叠或打开

  1. package com.easytalent.storage.dao.impl;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. import com.easytalent.base.dao.impl.GenericDaoImpl;
  5. import com.easytalent.storage.dao.AuthorityDao;
  6. import com.easytalent.storage.model.Authority;

  7. public class AuthorityDaoImpl extends GenericDaoImpl<Authority, Long> implements AuthorityDao {
  8.     public AuthorityDaoImpl() {
  9.         super(Authority.class);
  10.     }

  11.     @Override
  12.     public int deleteAuthority(Long roleId) throws Exception {
  13.         Object[] paramArray = null;
  14.         List<Object> param = new ArrayList<Object>();
  15.         String hql = "delete from Authority t where t.roleId = ? ";
  16.         param.add(roleId);
  17.         paramArray = param.toArray();
  18.         return this.execByHql(hql, paramArray);
  19.     }

  20.     @Override
  21.     public List<String> getByRoleId(Long roleId) {
  22.         Object[] paramArray = null;
  23.         List<Object> param = new ArrayList<Object>();
  24.         //因为 authority 和sysmodel是多对一,所以,查询多条authority势必会发送多条语句去查询sysmodel
  25.         //为了避免这个问题,用复杂的hql关联查询,返回obj[]的list
  26.         String hql = "select s.modelName from Authority t join t.sysmodel s where t.roleId = ? ";
  27.         param.add(roleId);
  28.         paramArray = param.toArray();
  29.         List<String> authorlist = this.findByHqlReturnObjectArray(hql, paramArray);
  30.         return authorlist;
  31.     }
  32. }


Struts.xml配置:

点击(此处)折叠或打开

  1. <package name="role" namespace="/role" extends="struts-elearning">
  2.         <action name="roleManager*" class="roleManagerAction" method="{1}">
  3.             <result name="list">/jsp/common/RoleManagerList.jsp</result>
  4.             <result name="edit">/jsp/common/RoleManagerEdit.jsp</result>
  5.             <result name="detail">/jsp/common/RoleManagerEdit.jsp</result>
  6.         </action>
  7.     </package>

转载于:https://my.oschina.net/sky2008/blog/525270