有bug請在評論區留言

這是個十分簡單的許可權實現,後端採用SSM框架,前段展示層使用ztree(ztree官網),實現控制則使用jsp自定義的判斷標籤;

第一步:新建power資料庫。

使用者表user,權利表power,使用者-權利關係表userPower,

/*
Navicat MySQL Data Transfer

Source Server         : 123
Source Server Version : 50610
Source Host           : 127.0.0.1:3306
Source Database       : power

Target Server Type    : MYSQL
Target Server Version : 50610
File Encoding         : 65001

Date: 2018-01-15 21:07:24
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for power
-- ----------------------------
DROP TABLE IF EXISTS `power`;
CREATE TABLE `power` (
  `pId` int(4) NOT NULL AUTO_INCREMENT,
  `pName` varchar(25) DEFAULT NULL,
  PRIMARY KEY (`pId`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of power
-- ----------------------------
INSERT INTO `power` VALUES ('1', '吃');
INSERT INTO `power` VALUES ('2', '吃飯');
INSERT INTO `power` VALUES ('3', '吃麵條');
INSERT INTO `power` VALUES ('4', '吃零食');
INSERT INTO `power` VALUES ('5', '喝');
INSERT INTO `power` VALUES ('6', '喝芬達');
INSERT INTO `power` VALUES ('7', '喝可樂');
INSERT INTO `power` VALUES ('8', '嘴');
INSERT INTO `power` VALUES ('9', '說話');
INSERT INTO `power` VALUES ('10', '噴人');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `uId` int(4) NOT NULL AUTO_INCREMENT,
  `uName` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`uId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin');
INSERT INTO `user` VALUES ('2', 'tom');
INSERT INTO `user` VALUES ('3', 'jack');

-- ----------------------------
-- Table structure for userpower
-- ----------------------------
DROP TABLE IF EXISTS `userpower`;
CREATE TABLE `userpower` (
  `uPId` int(4) NOT NULL AUTO_INCREMENT,
  `uPUId` int(11) DEFAULT NULL,
  `uPPId` int(11) DEFAULT NULL,
  PRIMARY KEY (`uPId`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of userpower
-- ----------------------------
INSERT INTO `userpower` VALUES ('1', '1', '1');
INSERT INTO `userpower` VALUES ('12', '2', '1');
INSERT INTO `userpower` VALUES ('13', '2', '2');
INSERT INTO `userpower` VALUES ('14', '2', '3');
INSERT INTO `userpower` VALUES ('15', '2', '4');
INSERT INTO `userpower` VALUES ('16', '2', '5');


資料庫完成,開始web部分

第二步:新建maven專案

新增專案相關jar包,這是專案的架構,biaoqian包是存放jsp自定義標籤的處理類


程式碼貼出關鍵部分

controller層程式碼:

package cn.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;

import cn.pojo.Power;
import cn.pojo.User;
import cn.pojo.UserPower;
import cn.service.UserPowerService;
import cn.service.UserService;

@Controller
@RequestMapping("power")
public class PowerController {

	@Resource
	private UserService userService;

	@Resource
	private UserPowerService userPowerService;

	/**
	 * 登入
	 * 
	 * @param request
	 * @param u
	 * @param model
	 * @return
	 */
	@RequestMapping("login")
	public String login(HttpServletRequest request, User u, Model model) {
		User user = userService.login(u);
		if (user == null) {
			return "redirect:/login.jsp";
		}
		HttpSession session = request.getSession();
		session.setAttribute("USER_LOGIN", user);
		if (user.getuName().equals("admin")) {
			List<User> list_user = userService.getAllUser();
			session.setAttribute("list_user", list_user);
			return "admin";
		}
		return "welcome";
	}

	/**
	 * 非同步方法,根據uid獲取相應許可權list
	 * 
	 * @param uId
	 * @return
	 */
	@RequestMapping("getPowerByUId")
	@ResponseBody
	public String getPowerByUId(@RequestParam("uId") String uId) {
		List<UserPower> i = userPowerService.getPowerByUId(Integer.parseInt(uId));
		return JSONArray.toJSONString(i);
	}

	@RequestMapping("updatePower")
	public String updatePower(@RequestParam("uId") String uId, @RequestParam("pow") String pow) {
		userPowerService.deletePower(Integer.parseInt(uId));// 增加前先刪除具有的許可權
		String[] p = pow.split(",");
		UserPower up = new UserPower();
		for (String power : p) {
			if (power.length() > 0) {
				up.setuPUId(Integer.parseInt(uId));
				up.setuPPId(Integer.parseInt(power));
				userPowerService.addPower(up);// 增加許可權
			}
		}
		return "admin";
	}
}
兩個service的方法:
package cn.service;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import cn.pojo.UserPower;

public interface UserPowerService {
	// 根據uid查出具有的許可權
	List<UserPower> getPowerByUId(Integer uId);

	// 增加許可權
	int addPower(UserPower userPower);

	// 刪除許可權
	int deletePower(Integer uId);
}






package cn.service;

import java.util.List;

import cn.pojo.User;

public interface UserService {
	// 登入
	User login(User u);

	// 獲得所有使用者
	List<User> getAllUser();
}

jsp頁面有3個,login.jsp   welcome.jsp    admin.jsp,這裡的login.jsp就不用說了吧,一個輸入框輸入姓名後,去資料庫查是否存在這個人,很簡單;

welcome.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="/WEB-INF/powertag.tld"  prefix="yu" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'welcome.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">
	-->

  </head>
  
  <body>
  我是${USER_LOGIN.uName },<br/>
  我具有:<hr/>
  <p style="color:red;">
  <yu:power power="吃">吃,<br/></yu:power>
  <yu:power power="吃飯">吃飯,<br/></yu:power>
  <yu:power power="吃麵條">吃麵條,<br/></yu:power>
  <yu:power power="吃零食">吃零食,<br/></yu:power>
  <yu:power power="喝">喝,<br/></yu:power>
  <yu:power power="喝芬達">喝芬達,<br/></yu:power>
  <yu:power power="喝可樂">喝可樂,<br/></yu:power>
  <yu:power power="嘴">嘴,<br/></yu:power>
  <yu:power power="說話">說話,<br/></yu:power>
  <yu:power power="噴人">噴人,<br/></yu:power>
  </p>
  <hr/>
   功能的
  </body>
</html>

admin.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'admin.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">
	-->

</head>

<body>
	<p>你想修改誰的許可權:</p>
	<c:forEach var="list_user" items="${list_user }">
		<c:if test="${list_user.uName!='admin' }">
			<input type="radio" name="uName" value="${list_user.uId }" />${list_user.uName }
  	</c:if>
	</c:forEach>

	<div id="ztree" style="display:none;">
		<ul id="baseTree" class="ztree" style="width:260px; overflow:auto;"></ul>
		<button id="btn">提交</button>
	</div>
</body>
</html>
<link rel="stylesheet" type="text/css"
	href="ztree/css/zTreeStyle/zTreeStyle.css">
<script type="text/javascript" src="js/jquery-1.8.0.js"></script>
<script type="text/javascript" src="ztree/jquery.ztree.all-3.5.js"></script>
<script>
	//$("input[name=uName]:checked")
	//顯示已有許可權
	$("input[name=uName]").click(function() {
		var uId = $("input[name=uName]:checked").val();
		$("#ztree").css("display", "block")
		var treeObj = $.fn.zTree.getZTreeObj("baseTree");
		treeObj.checkAllNodes(false); //所有節點取消選中
		treeObj.expandAll(false); //所有節點關閉
		$.post("power/getPowerByUId?uId=" + uId, function(data) {
			var v = JSON.parse(data);
			for (var i = 0; i < v.length; i++) {
				var node = treeObj.getNodeByParam("value", v[i].uPPId, null);
				treeObj.expandNode(node, true, false); //指定選中ID節點展開
				treeObj.checkNode(node); //指定節點選中
			}
		}, "text")
	})

	//修改許可權
	$("#btn").click(function() {
		var pow = "";
		var uId = $("input[name=uName]:checked").val()
		var treeObj = $.fn.zTree.getZTreeObj("baseTree");
		var nodes = treeObj.getCheckedNodes(true);
		for (var i = 0; i < nodes.length; i++) {
			pow = pow + "," + nodes[i].value;
		}
		location.href = "power/updatePower?uId="+uId+"&pow="+pow;
	})
	//設定ztree
	var setting = {
		check : {
			chkboxType : {
				"Y" : "ps",
				"N" : "s"
			}, //勾選checkbox對於父子節點的關聯關係,取消勾選時不關聯父  
			chkStyle : "checkbox",
			enable : true //是否複選框  
		},
		data : {
			simpleData : {
				enable : true
			}
		}
	};
	var zNodes = [ {
		id : 1,
		name : "吃",
		value : "1"
	}, {
		id : 11,
		pId : 1,
		name : "吃飯",
		value : "2"
	}, {
		id : 12,
		pId : 1,
		name : "吃麵條",
		value : "3"
	}, {
		id : 13,
		pId : 1,
		name : "吃零食",
		value : "4"
	}, {
		id : 2,
		name : "喝",
		value : "5"
	}, {
		id : 21,
		pId : 2,
		name : "喝芬達",
		value : "6"
	}, {
		id : 21,
		pId : 2,
		name : "喝可樂",
		value : "7"
	}, {
		id : 3,
		name : "嘴",
		value : "8"
	}, {
		id : 31,
		pId : 3,
		name : "說話",
		value : "9"
	}, {
		id : 32,
		pId : 3,
		name : "噴人",
		value : "10"
	}
	]
	$.fn.zTree.init($("#baseTree"), setting, zNodes);
</script>
請注意welcome.jsp中 <%@ taglib uri="/WEB-INF/powertag.tld"  prefix="yu" %> 這段程式碼,這是自定義標籤的引用。

下面開始自定義一個jsp判斷標籤,簡單的哦

jsp標籤建立分3步,先建立處理類,在編寫tid檔案,最後引用。

處理類:

package cn.biaoqian;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TagSupport;

import cn.pojo.Power;
import cn.pojo.User;


/**
 * @author Yu
 *
 */
public class Yu extends TagSupport {


	private PageContext pageContext;

	private String power;

	// 設定PageContext物件
	public void setPageContext(PageContext pageContext) {
		this.pageContext = pageContext;
	}

	public void setPower(String power) {
		this.power = power;
	}

	/**
	 * 標籤開始處理..呼叫的方法
	 * 
	 */
	@Override
	public int doStartTag() throws JspException {
		try {
			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
			HttpSession session = request.getSession();
			User u = (User) session.getAttribute("USER_LOGIN");
			System.out.println(u);
			List<Power> power = u.getPower();
			for (int i = 0; i < power.size(); i++) {
				if (power.get(i).getpName().equals(this.power)) {
					// 允許訪問標籤body
					return BodyTagSupport.EVAL_BODY_INCLUDE;// 返回此則執行標籤body中內容,SKIP_BODY則不執行
				}
			}
			return BodyTagSupport.SKIP_BODY;
		} catch (Exception e) {
			return BodyTagSupport.SKIP_BODY;
		}
	}

	/**
	 * 
	 * 標籤處理結束的呼叫的方法
	 */
	@Override
	public int doEndTag() throws JspException {
		return super.doEndTag();
	}

	/**
	 * 
	 * 釋放資源
	 */
	@Override
	public void release() {
		super.release();
	}

}
powertag.tid檔案,注意這個檔案位置在WEB-INF目錄下,與web.xml同級別:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<!-- 標籤描述TLD檔案 -->

<taglib>
    <tlib-version>1.1</tlib-version>
    <jsp-version>1.2</jsp-version>
    
    <!-- 預設字首名 -->
    <short-name>yu</short-name>
    
    <uri>http://www.mytaglib.com/taglib</uri> 
    <display-name>MyDateTaglib</display-name>
    <description>My date taglib!</description>  
      
    <tag>
        <name>power</name>
        <tag-class>cn.biaoqian.Yu</tag-class>
        
        <attribute>
            <name>power</name>
            <!-- 屬性是否必須 -->
            <required>true</required>
            <!-- 屬性是否支援小指令碼 EL表示式 -->
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        
    </tag>
    
</taglib>

最後在需要引用的介面引用
<%@ taglib uri="/WEB-INF/powertag.tld"  prefix="yu" %>

普通成員效果圖:


admin效果圖:


程式碼完成!

結束語:給與沒有許可權設計思路小夥伴的一個方法,僅作為案例(樣式什麼的隨便啦)

轉載請註明出處!