第一步:定義標籤格式java
以下圖先在安全目錄下創建一個tld文件web
內容代碼以下安全
<?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">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>permission</short-name>
<uri>http://com.keepmoving.cn/</uri>
<tag>
<name>permission</name>
<tag-class>com.keepmoving.util.PermissionTag</tag-class>
<attribute>
<name>opreator</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue><!-- 是否支持惡劣表達式 -->
<type>java.lang.String</type>
<description>示例:acApplication/forMain.do</description>
</attribute>
<attribute>
<name>parentNodeName</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue><!-- 是否支持惡劣表達式 -->
<type>java.lang.String</type>
<description>示例:acApplication/forMain.do</description>
</attribute>
</tag>
</taglib>session
其中permission爲標籤名字(在jsp中將會用到),com.keepmoving.util.PermissionTag爲標籤後臺代碼的實現類,此爲標籤的關鍵操做,java.lang.String,標籤的數據的值類型,將與實現類映射的屬性數據類型保持一致,<attribute>爲標籤屬性,能夠添加多個將與實現類映射的屬性保持一致。jsp
第二步:編寫自定義標籤實現類ide
package com.keepmoving.util;ui
import java.util.Map;this
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TagSupport;spa
import com.keepmoving.entity.User;.net
/**
* 自定義標籤實現類
* @author Administrator
*
*/
public class PermissionTag extends TagSupport{
private static final long serialVersionUID = 1L;
private String opreator;//操做類型 acApplication/forMain.do
private String parentNodeName;//父節點名稱
@Override
public int doStartTag() throws JspException {
HttpSession session = pageContext.getSession();
//判斷是否有權限訪問
if (isOperCanAccess(session, opreator)) {
//容許訪問標籤body
return BodyTagSupport.EVAL_BODY_INCLUDE;// 返回此則執行標籤body中內容,SKIP_BODY則不執行
} else {
return BodyTagSupport.SKIP_BODY;
}
}
/**
* ]判斷按鈕操做權限
* @param request
* @param opreator
* @return
*/
private boolean isOperCanAccess(HttpSession session,String opreator){
User user = (User)session.getAttribute("user");
Map<String, Object> mapButton = user.getMenuList();
if(user.getType()==0){
return true;
}else if(mapButton.containsKey(opreator)){
return true;
}else{
return false;
}
}
public String getOpreator() {
return opreator;
}
public void setOpreator(String opreator) {
this.opreator = opreator;
}
public String getParentNodeName() {
return parentNodeName;
}
public void setParentNodeName(String parentNodeName) {
this.parentNodeName = parentNodeName;
}
}
第三步:界面調用
jsp界面引入<%@ taglib prefix="btn" uri="/WEB-INF/tags/permission.tld" %>之定義標籤
而後在jsp的按鈕位置插入以下標籤完成按鈕控制操做。
<btn:permission parentNodeName="用戶列表" opreator="8615">
<a href="${pth}/main/toUserAddorUpdate"
style="margin-top: 5px;margin-right: 10px"
class="navbar-link navbar-link-type btn-spacial">
<span class="glyphicon glyphicon-pencil"></span>新增
</a>
</btn:permission>
說明:parentNodeName="用戶列表"爲按鈕的父節點名稱,此處opreator="8615"爲按鈕的惟一標識code。