최근에 사용자의 액세스 모듈 (권한)을 제어 해야하는 웹 사이트 유형 프로젝트에서 작업하고 있으므로 간단한 권한 제어 기능 세트가 설계 및 구현됩니다.
1. 데이터베이스 설계
사용자 : 사용자
모듈 : 모듈
SQL 코드 :
/*대상 서버 유형 : MySQLTARGET 서버 버전 : 50628File 인코딩 : 65001Date : 2016-08-26 10 : 35 : 28*/set foreign_key_checks = 0;--------------------------------------------------------------``````````````````````````````````( NULL AUTO_INCREMENT,`MODULE 'VARCHAR (30) 기본 NULL NULL 주석'模块 ',`PID` int (10) 기본 NULL 주석'上一级 id ',`level` int (4) 기본 NULL 주석'级别 ', 기본 키 ('id` ------------------------------ Table structure for `users`-- ----------------------------DROP TABLE IF EXISTS `users`;CREATE TABLE `users` ( `user_code` varchar(10) NOT NULL COMMENT '用户代码', `user_name` varchar(40) DEFAULT NULL COMMENT '用户名', `user_password` varchar(100) DEFAULT NULL COMMENT '密码', `qq` varchar(15) DEFAULT NULL COMMENT 'qq', `msn` varchar(50) DEFAULT NULL COMMENT 'msn', `demo` varchar(100) DEFAULT NULL COMMENT '备注', `auth_code` text COMMENT '权限码', PRIMARY KEY (`user_code`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of users-- ---------------------------- 1. 백엔드 구현 <br /> SSM+프리 마커 프레임 워크는 프로젝트에서 권한 트리의 데이터 구조로 권한을 캡슐화 한 다음이를 JSON 형식으로 변환하는 데 사용됩니다.
1) 디스플레이 레이어는 Ztree Tree (setUserauthontree.html)를 채택합니다.
<! doctype html> <html> <head> <#include "common/res.html"/> <script src = "$ {base.ctx} /js/layer-v2.1/laypage/laypage.js"> </script> <link href = "$ {base.ctx} /js/layer-v2.1/laypage/skin/laypage.css"rel = "stylesheet"type = "text/css"/> <script src = "$ {base.ctx}/js/layer-v2.1/layer/layer/layer.js">-/script> 스타일-> <link href = "$ {base.ctx} /component/ztree/css/ztreestyle/ztreestyle.css"rel = "Stylesheet"type = "text/css"/> <script type = "text/javascript" src = "$ {base.ctx}/component/ztree/js/jquery.ztree.core-3.5.js"> </script> <script type = "text/javaScript"src = "$ {base.ctx}/component/ztree/js/jquery.ztree.ztree.5 type = "text/css">. Blue-Madison {Border : 1px solid #7ca7cc; 테두리 탑 : 0;}. 캡션 {배경색 : #578ebe; 국경 바닥 : 0; 패딩 : 0 10px; 마진 바닥 : 0; 색상 : #fff;} </style> </head> <body> <div style = "Overflow-Y : Auto; width : 400px; 높이 : 550px;"> <div id = "ztree"> <ul id = "treedemo"> </ul> </div> </div> <div> <div align = "style" "Style" onclick = "editModle ()"> ok </button> <버튼 유형 = "button"id = "cance"> close </div> </div> </div> </div> <cript> $ ( "Document"). ready (function () {$ .ajax ({type : "post :"$ {base.ctx}/getUp/getUperWertmbyId ", {id ":"$ {userId} "},"JSON ", 성공 : ZTREEOBJ = $ .fn.ztree.init ("#treedemo ") // 트리를로드 var ztreeobj; // 심층적 인 사용에 대해서는 API 문서 (구성 설정에 대한 자세한 설명) var 설정 = {view : {// dblclickexpand : false, showline : true, // 노드 간의 연결이 표시됩니다}, 점검 : {enable : true, // nocheckinherit : false, chkstyle : "chkbox" "n": "ps"}, // autochecktrigger : true}, 콜백 : {oncheck : ztreeoncheck,}}; // checkbox 클릭 콜백 이벤트 함수 ZtreeOncheck (이벤트, treeId, treenode) { /* var ztree = $ .fn.ztree.getztreeobj ( "treedemo"); var ChangeNodes = ztree.getChangeCheckedNodes (); for (var i = 0; i <changenodes.length; i ++) {var treenode = changenodes [i]; } */}; 함수 editModle () {var rootid = null; var midid = null; var minid = null; var treeobj = $ .fn.ztree.getztreeobj ( "treedemo"); var 노드 = treeObj.getCheckedNodes (); for (var i = 0; i <nodes.length; i ++) {if (nodes [i] .level == 0) {rootid = rootid+","+노드 [i] .id; } if (노드 [i] .level == 1) {midid = midid+","+노드 [i] .id; } if (노드 [i] .level == 2) {minid = minid+","+노드 [i] .id; }} if (rootid! = null) {rootid = rootid.substring (5, rootid.length); } if (midid! = null) {midid = midid.substring (5, midid.length); } if (minid! = null) {minid = minid.substring (5, minid.length); } $ .ajax ({type : "post", url : "$ {base.ctx}/setup/updateUerRightMaskByajax", datatype : "json", data : {rootid ":"midid ":"minid ": minid,"userid ":"$ {userid} "}}}} if (rate = "1") {layer.msg (settimeout () {top.dialog.get ( "set-dialog"). } // 닫기 $ ( "#cancel"). (function () {top.dialog.get ( "set-dialog"). close (). remove ();}); </script> </body> </html> 디스플레이 효과는 다음과 같습니다.
2) 컨트롤러 제어 계층은 SpringMVC를 사용합니다
제어 계층에서 데이터를 JSON 형식으로 변환하여 디스플레이 레이어로 보냅니다.
/** * @fun 지점 사용자 권한 받기 * @Author pi feng * @Date 2016/8/25 * @Param Session * @Param id * @param substoreid * @return */@requestmapping ( "getUserRightMaskById") @ResponseBody public object getUserRightMaskById (httpsessions, string, string). substoreId = stringUtils.isempty (subsoreId)? string.valueof (session.getAttribute ( "subsoreId")) : substoreId; // 호텔인지 여부 또는 여관 목록 <map <string, object >> versionsList = this.setUpService.gethotElversions (substoreId); 개체 버전 = versionsList.get (0) .get ( "버전"); Map <String, Object> HotelMap = New Hashmap <String, Object> (); if ((null! = versionsList) && (versionsList.size ()! = 0)) {// 목록이 비어 있지 않아 if ( "완료".equals (versions (versions) (versions))) {// query 호텔 허가 호텔 map = this.grightService.getUrightMaskOntree (coundsoRight, id, id, "완료"); } else if ( "simple".equals (versions)) {// inn // query inn 권한 트리 호텔 map = this.rightmaskservice.getUrightMaskOntree (substoreId, id, "simple"); }} map <string, object> resultmap = new Hashmap <String, object> (); resultmap.put ( "datas", hotelmap); return jsonobject.tojsonstring (resultmap, serializerfeature.writemapnullvalue); } 3) 서비스 서비스 계층은 권한을 Ztree 형식을 만족시키는 트리 데이터 구조로 캡슐화합니다.
/** * @fun 분기 사용자 권한 가져 오기 * @author pi feng * @date 2016/8/25 * @param substoreid * @param id * @param versions * @return map <string, object> */@override public map <string, object> getuserrightmaskontree (string sortoreid, string id, string) {map <string, object> userrightmask = this.irightmaskdao.getuserrightmaskbysubandid (substoreid, id); list <map <string, object >> listone = new arraylist <map <String, object >> (); list <map <string, object >> listtwo = new ArrayList <map <String, Object >> (); // list <map <string, object >>> listthree = new ArrayList <map <String, Object >> (); List <map <String, Object >>> resultList = new ArrayList <map <String, Object >> (); if (versions.equals ( "complete")) {// hotel listone = this.irightmaskdao.getrightmaskonhotelone (); listtwo = this.irightmaskdao.getrightmaskonhoteltwo (); // listthree = this.irightmaskdao.getrightmaskonhotelthree (); PackagingTotWotree (resultList, Listone, ListTwo, UserRightMask); } else if (versions.equals ( "simple")) {// inn listone = this.irightmaskdao.getrightmaskontavernone (); listtwo = this.irightmaskdao.getrightmaskontaverntwo (); // listthree = this.irightmaskdao.getrightmaskontavernthree (); PackagingTotWotree (resultList, Listone, ListTwo, UserRightMask); } map <String, object> map = new Hashmap <String, Object> (); map.put ( "data", resultList); 리턴 맵; }/** * @function acapsulate acapsulate accapsulate * @author pi feng * @date 2016/8/26 * @param resultlist * @param listone * @param authcode * @return void */private void packagingToonetree (list <map <string, object >> resultlist, list <string, object >> map <string, Object >>) 0; i <listone.size () {map <string, object> rootmap <string, object> (); rootmap.put ( "id", listone.get (i) .get ( "id")); rootmap.put ( "name", listone.get (i) .get ( "module")); if (validaterightmask (listone, authcode, i)! = -1) {rootmap.put ( "Checked", true); } else {rootmap.put ( "Checked", false); } resultList.add (rootmap); }}/** * @function acappulate * @author pi feng * @date 2016/8/26 * @param resultlist * @param listone * @param listtwo * @param authcode * @return void */private void packagingtotwotree (list <map <string, object >> resultlist, list <string, object <map <map <string,) Object >> listtwo, map <string, object >> authcode) {for (int i = 0; i <listone.size (); i ++) {list <map <string, object >> midlist = new arraylist <map <string, object >> (); for (int J = 0; Map <string, object> midmap = new Hashmap <String, object> (); midmap.put ( "id", listtwo.get (j) .get ( "id")); midmap.put ( "name", listtwo.get (j) .get ( "module")); midmap.put ( "Children", Minlist); if (validaterightmask (listtwo, authcode, j)! = -1) {midmap.put ( "Checked", true); } else {midmap.put ( "Checked", False); } midlist.add (midmap); }} map <string, object> rootmap = new Hashmap <String, object> (); rootmap.put ( "id", listone.get (i) .get ( "id")); rootmap.put ( "name", listone.get (i) .get ( "module")); rootmap.put ( "Children", Midlist); if (validaterightmask (listone, authcode, i)! = -1) {rootmap.put ( "Checked", true); } else {rootmap.put ( "Checked", false); } resultList.add (rootmap); }}/** * @function은 세 번째 레벨 트리를 캡슐화합니다 * @Author pi feng * @date 2016/8/26 * @param resultlist * @param listone * @param listtwo * @param listtwo * @param authcode * @return void */private void packagingttothreetree (목록 <map <map <map <map <map <map <risglist, ristlist, ristlist, list <map. listone, listone, list <map <string, object >> listtwo, list <map <string, object >> listthree, map <string, object> authcode) {for (int i = 0; i <listone.size (); i ++) {list <map <string, object >> midlist = new arraylist <string, object >> (); for (int J = 0; for (int k = 0; k <listthree.size (); k ++) {map <string, object> minmap = new Hashmap <string, object> (); if (listthree.get (k) .get ( "pid"). tostring () .equals (listtwo.get (j) .get ( "id"). tostring ())) {minmap.put ( "id", listthree.get (k)); get ( "id"); minmap.put ( "name", listthree.get (k) .get ( "module")); if (validaterightmask (listthree, authcode, k)! = -1) {minmap.put ( "Checked", true); } else {minMap.put ( "Checked", False); } minlist.add (minmap); }} map <string, 객체> midmap = new Hashmap <String, object> (); midmap.put ( "id", listtwo.get (j) .get ( "id")); midmap.put ( "name", listtwo.get (j) .get ( "module")); midmap.put ( "Children", Minlist); if (validaterightmask (listtwo, authcode, j)! = -1) {midmap.put ( "Checked", true); } else {midmap.put ( "Checked", False); } midlist.add (midmap); }} map <string, object> rootmap = new Hashmap <String, object> (); rootmap.put ( "id", listone.get (i) .get ( "id")); rootmap.put ( "name", listone.get (i) .get ( "module")); rootmap.put ( "Children", Midlist); if (validaterightmask (listone, authcode, i)! = -1) {rootmap.put ( "Checked", true); } else {rootmap.put ( "Checked", false); } resultList.add (rootmap); }}/** * @function 목록에 AuthCode에 권한 코드가 있는지 확인하십시오 * @Author pi feng * @Date 2016/8/26 * @param list * @param authcode * @param i * @rereturn int */private int validaterightmask (list <map <string, object >> map <string> authcode, int i) authcode.get ( "auth_code")! = null? authcode.get ( "auth_code"). toString () : ""; if (! stringUtils.isempty (rightmask)) {rightmask = rightmask.replace ( ";", ","); 문자열 [] array = rightmask.split ( ","); for (int j = 0; 문자열 listrightmask = list.get (i) .get ( "id"). tostring (); if (arryrightmask.equals (listrightmask)) {return 1; }}} else {return -1; } 반환 -1; } 4) 데이터베이스를 쿼리하여 사용자 권한을 얻습니다
에이. 데이터 계층의 권한 수준에 따라 모듈 테이블에서 다른 수준의 권한을 꺼내십시오.
id, 모듈, PID, 레벨에서 레벨에서 레벨을 선택하십시오 = '0'id, 모듈, PID, 레벨 = '1'모듈에서 레벨을 선택하십시오. id, 모듈, PID, 레벨 = '2'
비. 사용자 테이블에서 사용자 (허가 코드)의 모든 권한을 꺼내십시오.
user_code = 'pifeng'인 사용자에서 auth_code를 선택하십시오.
기음. 권한을 저장할 때, 다른 수준 사이의 권한 코드는 영국 세미콜론에 의해 분리되며 같은 수준 사이의 권한 코드는 영국 쉼표로 분리됩니다. ",". 예를 들어 : 1,2,3,4,6,7,8,9,10,11,12; 13,14,15,16,18,19,20,21,22,23,24,25,26,36,37,27,28,29,30,31,32,33,35,38,39,40,41,42,43,44 , 45,46,47,49,50,51,52,53,54,56,57,58,59,60,61,62,63,64,133,65,66,68,69,70,71,72,73,75,1 26,127,128,129,130,131,76,77,78,79,80,81,82,83,84,85,86,87,88,99,124,134,135,136,140,141,90,91,92,93,94,95,93,94,95,93,94,95,93,94,93,93,94,92,93,94,93,93,92,93,93,94,95,93,94,93,94,93,94,93,94,93,94,95,93,94,93,94,93,94,95,93,94,93,9OC, 6,97,98,137,138,139,100,101,102,103,106,107,132,108,109,110,111,112,113,114,116,125,117,118,119,120,121,122
5) 프리 마커 태그를 사용하여 페이지 함수 모듈이 사용자의 권한 코드에 따라 표시되는지 여부를 제어합니다.
에이. XML 파일의 프리 마커 구성
<bean id = "freemarkerConfig"> <!-템플릿 로딩 경로-> <속성 이름 = "templateLoaderPath"> <value>/web-inf/ftl/</value> </property> <속성 이름 = "FreemarkErvariables"> <map> <Entry key = "xml_escape"value-ref = "fmxmllescape"/>>>>>>>>>>>>>>>>>>>. 이름 = "FreemarkerSettings"> <props> <prop key = "tag_syntax"> auto_detect </prop> <prop key = "template_update_delay"> 0 </prop> <prop key = "default_encoding"> utf-8 </prop> <prop key = "output_encoding"> utf-8 <prop> <prop> key = "locale"> zh_cn </prop> <prop key = "date_format"> yyyy-mm-dd </prop> <prop key = "time_format"> hh : mm : ss </prop> <prop key = "number_format"> 0. ###### </prop> <prop key = "datetime_format"> yyyyyyy-mm : prop : procy-mm dm : <!-null 값 처리-> <prop key = "classic_compatible"> true </prop> <!-FTL 템플릿을 자동으로 가져 와서 네임 스페이스로 "기본"별칭을 네임 스페이스로 사용합니다-> <prop key = "auto_import"> inc/spring.ftl as base </prop> </props> </bean> <bean id = "bean id ="fmxmlescape "/> id = "FreemarkerViewResolver"> <속성 이름 = "접미어"value = ". html"/> <속성 이름 = "cache"value = "false"/> <property name = "viewClass"value = "org.springframework.web.serv.servlet.view.freemarker.freemarkieview"/> <property name = "" value = "text/html; charset = utf-8"> </property> <!-고정 예외 : 기존 모델로 인해 세션 속성을 노출시킬 수 없습니다-> <propertion override "value ="true "/<property name ="exposeerequestattributes "value ="true "/> <propossationattributes. 이름 = "exposeSpringMacroHelpers"value = "true"/> <!-이 변수 값은 pagecontext.request, page usage method : request.contextpath-> <property name = "requestContextAttribute"value = "request"/<property name = "attributesmap"> 이전에 정의한 도구 클래스에 연결-> <bean/> </enterd> </map> </property> </bean>
비. TemplatemetheDModel 클래스를 상속받을 수 있도록 클래스를 작성하고 프리 마커 사용자 정의 메소드를 구현하여 페이지 모듈이 로그인을 표시하고 사용자 권한 코드를 세션에 저장 한 다음 세션에서 허가를 얻습니다. 예는 다음과 같습니다.
public class menufunction은 templatemethodmodel {@override public object exec (list arg0)를 templatemodelexception {int level = integer.valueof (arg0.get (0) .toString ()); // 모듈 레벨 int modelId = integer.valueof (arg0.get (1) .toString ()); // 모듈 ID int count = 0; //이 모듈에 대한 권한 코드 httpservletRequest request = ((servletRequestAttributes) requestContexTholder.getRequestAttributes (). getRequest (); httpsession session = request.getSession (); Object o = session.getAttribute ( "Info"); if (o == null) false를 반환합니다. 정보 정보 = (정보) o; 문자열 authcode = info.getUser (). getAuthCode (); // 허가 코드 if (authcode.contains ( ";")) {string [] masks = authcode.split ( ";"); 문자열 [] m = 마스크 [level] .split ( ","); for (int i = 0; i <m.length; i ++) {if (modelid == integer.parseint (m [i])) {++ count; } else {count+= 0; }}}} if (count == 0) {return false; } else {return true; }}} 기음. 페이지에서 프리 마커 태그를 사용하고 모듈의 표시가 숨겨져 있습니다.
Menucall의 두 매개 변수, 첫 번째는 모듈 레벨이고 두 번째는 모듈 ID입니다.
예를 들어:
<#if menucall (1,122)> <li style = "line-height : 250%"> <a href = "#"id = "id ="booknew "> <i> </i> 예약 </a> </li> </#if>
위는 사용자의 액세스 모듈 제어의 일반적인 구현입니다 (권한).
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.