Vor kurzem arbeite ich an einem Website-Typ-Typ, bei dem das Zugriffsmodul (Berechtigungen) des Benutzers gesteuert werden muss. Daher wird eine einfache Reihe von Berechtigungssteuerungsfunktionen entworfen und implementiert.
1. Datenbankdesign
Benutzer: Benutzer
Module: Module
SQL -Code:
/*Zielservertyp: Mysqltarget Server Version: 50628File Codierung: 65001Date: 2016-08-26 10: 35: 28*/set fremd_key_checks = 0; Null auto_increment, `modul` varchar (30) Standardnull-Kommentar '模块',` pid` int (10) Standardnull-Kommentar '上一级 id', 'Level` int (4) Standardnull-Kommentar' 级别 ', Primärschlüssel (`id`) Engine = innodb default = utf8; ------------------------------ 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) Standard-Null-Kommentar 'qq', 'msn` varchar (50) Standardnull-Kommentar' MSN ',' Demo` varchar (100) Standardnull-Kommentar '备注', `auth_code` text 'text' 权限码 ', Primärschlüssel (` user_code`) Engine = innodb default = utf8;
1. Back-End-Implementierung <br /> Das SSM+Freemarker-Framework wird im Projekt verwendet, um Berechtigungen in die Datenstruktur des Berechtigungsbaums zu verkapulieren und es dann in das JSON-Format umzuwandeln.
1) Die Anzeigeschicht nimmt Ztree Tree an (setuserAuthontree.html)
<! DocType html> <html> <kopf> <#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.js"></script><!-- Introducing tree menu style-> <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 = "$ {Basis.ctx} /component/zree/jquy.zree.zree.zree.zree.zree.zree.zree.zree.zree.ze. Typ = "Text/CSS">. Blue-Madison {Border: 1PX Solid #7CA7CC; Border-Top: 0;}. Caption {Hintergrundfarbe: #578EBE; Grenzboden: 0; Polsterung: 0 10px; Randboden: 0; Farbe: #fff;} </style> </head> <body> <div style = "overflow-y: auto; width: 400px; Höhe: 550px;"> <div id = "ztree"> <ul id = "treedemo"> </ul> </div> <div> <div> <div> <div> <div> <div> <div Align = "center" style "style" onclick="editModle()">OK</button> <button type="button" id="cancel">Close</button> </div> </div> </div> <script> $("document").ready(function() { $.ajax({ type : "post", url : "${base.ctx}/Setup/getUserRightMaskById", Daten: {"ID": "$ {userId}"}, DataType: "JSON", Erfolg (Ergebnis) {ZtreeObj = $. // last den Baum var ztreeobj; // For in-depth use, please refer to the API documentation (detailed explanation of setting configuration) var setting = { view : { //dblClickExpand : false, showLine : true, //Does the connection between nodes be displayed}, check: { enable: true, //nocheckInherit: false, chkStyle: "checkbox", chkboxType: { "Y": "ps", "N": "ps"}, // autoChecktrigger: true}, callback: {onCheck: ztreeonCheck,}}; // Kontrollkästchen auf Callback -Ereignisfunktion ZTreeonCheck (Ereignis, TreeId, Treenode) { /* var ztree = $ .fn.ztree.getZtreeObj ("Treedemo"); var geänderteNodes = ztree.getchangecheckednodes (); für (var i = 0; i <geändert. } */}; Funktion editModle () {var rootId = null; var midid = null; var minid = null; var treeObj = $ .fn.ztree.getZtreeObj ("Treedemo"); var nodes = baumObj.getCheckednodes (); für (var i = 0; i <odes.length; i ++) {if (Knoten [i] .Level == 0) {rootId = rootId+","+Knoten [i] .Id; } if (Knoten [i] .Level == 1) {MIDID = MIDID+","+Knoten [i] .Id; } if (Knoten [i] .Level == 2) {minid = minid+","+Knoten [i] .id; }} if (rootId! = null) {rootId = rootId.substring (5, rootId.length); } if (midid! } if (minid! = null) {minid = minid.substring (5, minid.length); } $.ajax({ type : "post", url: "${base.ctx}/Setup/updateUserRightMaskByAjax", dataType : "json", data:{"rootId":rootId,"midId":midId,"minId":minId,"userId":"${userId}"}, success : function(result) { if(result=="1"){ layer.msg ("Empowered erfolgreich!"); } // Schließen Sie $ ("#covorn"). CLICK (function () {top.dialog.get ("set-dialog"). Close (). Remove ();}); </script> </body> </html> Der Anzeigeeffekt ist wie folgt:
2) Controller Control Layer verwendet SpringMVC
Konvertieren Sie in der Kontrollschicht die Daten in das JSON -Format und senden Sie sie an die Anzeigeschicht.
/** * @fun Get Branch User Berechtigungen * @Author pi feng * @date 2016/8/25 * @param session * @param id * @param Substoreid * @Return */@RequestMapping ("GetUserrightmaskbyId") @ResponDy Public Object Getusrightmasking (htttpSession, String Id, String Id, String Id, String Ids. Substoreid = Stringutils.isempty (Substoreid)? String.ValueOf (Session.GetAttribute ("Substoreid"): SubstoreId; // Beurteilen Sie, ob es sich um ein Hotel oder eine Inn -Liste <map <String, Object >> Versionslist = this.setupService.Gethotelversions (SubstoreId) handelt. Objektversionen = VersionSlist.get (0) .get ("Versionen"); Karte <String, Object> Hotelmap = New HashMap <String, Object> (); if ((null! } else if ("einfache" .Equals (Versionen)) {// inn // Abfrage Inn Berechtigungsbaumelement Hotelmap = this.rightmaskservice.getUserrightmaskonTree (Substoreid, ID, "einfach"); }} Map <string, Object> resultMap = new HashMap <String, Object> (); resultMap.put ("datas", Hotelmap); return jsonObject.tojonstring (resultmap, serializerFeature.writemapnullValue); } 3) Die Dienstleistungsschicht umfasst Berechtigungen in eine Baumdatenstruktur, die das Ztree -Format erfüllt
/** * @fun Get Branch User Berechtigungen * @author pi feng * @date 2016/8/25 * @param Substoreid * @param id * @param -Versionen * @return map <String, Objekt> */@Override public map <String, Object> GetUrightMaskonTree (String Substoreid, String id, String id, String id, String id, String id, String id, String id, String id, String id, {String -Version) {String -Versionen) {String -Versionen, {String -Versionen, {String -Versionen) {String -Version, {String -Version) {String -Versionen, {String -Versionen) {{String -Version> {{{map <String, Object>. userrightmask = this.irightmaskdao.getUserrightmaskbysubandid (Substoreid, ID); List <map <String, Objekt >> listone = new ArrayList <map <String, Objekt >> (); Liste <map <string, objekt >> listTWO = new ArrayList <map <String, Objekt >> (); // list <map <String, Objekt >>> listThree = new ArrayList <map <String, Objekt >> (); Liste <map <string, objekt >>> resultlist = new ArrayList <map <String, Objekt >> (); if (Versions.equals ("komplett") {// Hotel listone = this.irightmaskdao.getRightmaskonHotelone (); LISTTWO = this.irightmaskdao.getRightmaskonHoteltwo (); // listThree = this.irightmaskdao.getRightmaskonHoteltHee (); packagingTotWotree (Ergebnisliste, Listone, ListTWO, UserRightmask); } else if (Versions.equals ("einfach") {// inn listone = this.irightmaskdao.getRightmaskontaVernone (); LISTTWO = this.irightmaskdao.getRightmaskontaVerntWO (); // listThree = this.irightmaskdao.getRightmaskontaVernThree (); packagingTotWotree (Ergebnisliste, Listone, ListTWO, UserRightmask); } Map <string, object> map = new HashMap <String, Object> (); map.put ("data", resultlist); Rückgabekarte; }/** * @function Encapsulate a first-level tree* @author Pi Feng* @date 2016/8/26 * @param resultList * @param listOne * @param authCode * @return void */ private void packagingToOneTree(List<Map<String, Object>> resultList, List<Map<String, Object>> listOne, Map<String, Object>> authCode) { for (int i = 0; i <listone.size (); rootMap.put ("id", listone.get (i) .get ("id")); rootMap.put ("name", listone.get (i) .get ("modul"); if (validArtherInt mask (listOne, authCode, i)! = -1) {rootMap.put ("geprüft", true); } else {rootMap.put ("geprüft", false); } resultList.add (rootMap); } } /** * @function Encapsulate a secondary tree* @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<Map<String, Object>> listOne, List<Map<String, Object>> ListTWO, Map <String, Objekt >> AuthCode) {für (int i = 0; i <listone.size (); i ++) {list <map <String, Objekt >> midlist = new ArrayList <map <String, Objekt >> (); für (int j = 0; j <listtwo.size (); j ++) {if (listtwo.get (j) .get ("pid"). toString () .equals (listone.get (i) .get ("id"). toString ())) {list <map <map <map <map <string, Objekt >>> minlist = new Arraylist = new Arraylist <map <map <string, Objekt> () () () () (); Karte <string, Objekt> midmap = new HashMap <String, Object> (); Midmap.put ("id", listtwo.get (j) .get ("id")); Midmap.put ("Name", ListTwo.get (j) .get ("Modul")); Midmap.put ("Kinder", Minliste); if (validArtherInt mask (ListTWO, AuthCode, j)! = -1) {Midmap.put ("geprüft", true); } else {midmap.put ("geprüft", 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 ("modul"); RootMap.put ("Kinder", Midlist); if (validArtherInt mask (listOne, authCode, i)! = -1) {rootMap.put ("geprüft", true); } else {rootMap.put ("geprüft", false); } resultList.add (rootMap); } } /** * @function Encapsulate a third-level tree* @author Pi Feng* @date 2016/8/26 * @param resultList * @param listOne * @param listTwo * @param listTwo * @param authCode * @return void */ private void packagingToThreeTree(List<Map<String, Object>> resultList, List<Map<String, Object>> listOne, List <map <String, Objekt >> ListTWO, List <map <String, Objekt >> ListThree, map <String, Objekt> AuthCode) {für (int i = 0; i <listone.size (); i ++) {list <map <String, Objekt >> MidList = New ArrayList <map <string >> (); für (int j = 0; j <listTwo.size (); j ++) {if (listtwo.get (j) .get ("pid"). toString () .equals (listone.get (i) .get ("id"). toString ())) {list <map <map <map <map <string, Objekt >> minlist = new Arraylist <map <map <string, Objekt >> () () (); für (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 ("modul"); if (validArtherIntMask (ListThree, AuthCode, k)! = -1) {minmap.put ("geprüft", true); } else {minmap.put ("geprüft", false); } minlist.add (minmap); }} Map <string, Object> midmap = new HashMap <String, Object> (); Midmap.put ("id", listtwo.get (j) .get ("id")); Midmap.put ("Name", ListTwo.get (j) .get ("Modul")); Midmap.put ("Kinder", Minliste); if (validArtherInt mask (ListTWO, AuthCode, j)! = -1) {Midmap.put ("geprüft", true); } else {midmap.put ("geprüft", 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 ("modul"); RootMap.put ("Kinder", Midlist); if (validArtherInt mask (listOne, authCode, i)! = -1) {rootMap.put ("geprüft", true); } else {rootMap.put ("geprüft", false); } resultList.add (rootMap); }}/** * @Function Überprüfen Sie, ob in der Liste der Berechtigungscode in der Liste * @author pi feng * @date 2016/8/26 * @param list * @param AuthCode * @param i * @return int */private Int ValidaterInt Maska (liste <map <maper, Object >> listen, map < AuthCode.get ("auth_code")! = null? AuthCode.get ("auth_code"). toString (): ""; if (! Stringutils.isempty (rightmask)) {rightmask = rightmask.replace (";", ",", "); String [] array = rightmask.Split (","); für (int j = 0; j <arry.length; j ++) {String arrayRightmask = arry [j]; String listrightmask = list.get (i) .get ("id"). ToString (); if (arryrightmask.equals (listrightmask)) {return 1; }}} else {return -1; } return -1; } 4) Fragen Sie die Datenbank ab, um Benutzerberechtigungen zu erhalten
A. Nehmen Sie unterschiedliche Berechtigungsstufen aus der Module -Tabelle gemäß der Berechtigungsstufe in der Datenschicht heraus.
Wählen Sie ID, Modul, PID, Level aus Modulen wobei Level = '0' ID, Modul, PID, Level aus Modulen Wobei Level = '1' Wählen Sie ID, Modul, PID, Level aus Modulen, wobei Level = '2' wählen
B. Nehmen Sie alle Berechtigungen eines Benutzers (Berechtigungscode) in der Benutzertabelle heraus
Wählen Sie Auth_Code von Benutzern, wobei user_code = 'pifeng' '
C. Beim Speichern von Berechtigungen werden die Berechtigungscodes zwischen verschiedenen Ebenen durch das britische Semikolon getrennt; Zum Beispiel: 1,2,3,4,5,6,7,8,9,10,11,12; 13,14,15,16,17,18,19,20,21,22,23,24,25,26,36,37,27,28,29,30,31,32,33,34,35,38,39,40,41,42,433,44 , 45,46,47,48,49,50,51,52,53,54,56,57,58,59,60,61,62,63,64,133333,66,67,67,68,69,71,72,73,74,75,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,89,90,91,92,93,94,95,9 6,97,98,137,138,139,100,101,102,103,106,107,132,108,109,110,111,112,113,114,115,116,125,117,118,120,121,122
5) Verwenden Sie das Freemarker -Tag, um zu steuern, ob das Seitenfunktionsmodul gemäß dem Berechtigungscode des Benutzers angezeigt wird
A. FREEMARKER -Konfiguration in der XML -Datei
<bean id = "freemarkerConfig"> <!-Vorlage Ladepfad-> <Eigenschaft name = "templateloaderPath"> <wert>/web-inf/ftl/</value> </Eigenschaft> <Eigenschaft name = "freemarkervariable"> <map> <Eintragstastatur = "xml_esescape" -Vote-ref = "fmxiables"/mapta> <value-ref = " name = "freemarchersetts"> <props> <prop key = "tag_syntax"> auto_detekt </prop> <prop key = "template_update_delay"> 0 </prop> <props key = "default_encoding"> utf-8 </prop> <props key = "output_encoding"> utf-8 </propus </propus </props </props </props </props </propus </propus </propus </props> </propus </propus </propus </propus </propus </props </props </props </props </props </props </props <props. 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">yyyy-MM-dd HH:mm:ss</prop> <!-Null Value Processing-> <Prop Key = "Classic_Compatible"> True </prop> <!-Importieren Sie automatisch die FTL-Vorlage und verwenden Sie den Alias "Basis" als Namespace-> <prop key = "auto_import"> Inc/Spring.ftl As Base </prop> </props> </property> </lean> </lean> <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean <Bean; id = "Freemarkerviewresolver"> <Eigenschaft name = "suffix" value = ". value = "text/html; charSet = utf-8"> </property> <!-Behobene Ausnahme: Session-Attribut 'Substoreid' kann aufgrund eines vorhandenen Modells nicht freigesetzt werden. name = "exposespringMacroHelpers" value = "true"/> <!-Dieser variable Wert ist pageContext. Associate mit der Werkzeugklasse, die wir zuvor definiert haben-> <bean/> </Eintrag> </map> </property> </bean>
B. Schreiben Sie eine Klasse, um die Templatemethodmodel -Klasse zu erben, und implementieren Sie die benutzerdefinierte Freemarker -Methode, um zu steuern, ob das Seitenmodul die Anmeldung anzeigt, und speichern Sie den Benutzerberechtigungscode in die Sitzung, und erhalten Sie dann die Berechtigung aus der Sitzung. Hier ist ein Beispiel:
Public Class Menufunction implementiert templatemethodmodel {@Override public Object exec (list arg0) löst TemplatemodelException aus {int Level = Integer.ValueOf (arg0.get (0) .toString ()); // Modulstufe int modelid = integer.ValueOf (arg0.get (1) .toString ()); // Modul -ID int count = 0; // Sitzung festlegen, ob der Berechtigungscode für dieses Modul httpServletRequest Request = ((ServletRequestAttributes) RequestContexTHolder.getRequestAtributes ()). GetRequest (); HttpSession Session = Request.GetSession (); Object O = Session.getAttribute ("info"); if (o == null) return false; Info info = (info) o; String authCode = info.getUser (). GetAuthcode (); // Berechtigungscode if (AuthCode.Contains (";")) {string [] masken = authcode.split (";"); String [] m = masken [Ebene] .Split (","); für (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; }}} C. Verwenden Sie das Freemarker -Tag auf der Seite und steuern Sie die Anzeige des Moduls, die versteckt ist
Zwei Parameter in Menucall, das erste ist die Modulebene und die zweite ist die Modul -ID
Zum Beispiel:
<#if Menucall (1,122)> <li style = "Zeilenhöhe: 250%"> <a href = "#" id = "bookNew"> <i> </i> Buchung </a> </li> </#if>
Das obige ist die allgemeine Implementierung der Kontrolle des Benutzerzugriffsmoduls (Berechtigungen).
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.