DIV CSS 佈局教程網

Java 自定義標籤實戰:寫一個權限控制標籤
編輯:關於JavaScript     

自定義標籤能帶來兩大好處:一是頁面輸出邏輯封裝,二是把權限判斷這類橫向邏輯從 JSP 與 Servlet 中剝離出去。下面以「無權限則不渲染內容」為例,走一遍完整流程。

零、目標用法

最終希望在頁面中這樣寫:

<wxt:per uri="${pageContext.request.contextPath }/privilege/list"></wxt:per>

只有當前登錄用戶具備該 uri 的訪問權限時,標籤體中的內容才會輸出。

一、編寫標籤類

自定義標籤通常繼承 SimpleTagSupport:

package cn.com.liveuc.privilege.tag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import cn.com.liveuc.privilege.model.Privilege;
import cn.com.liveuc.privilege.model.Resource;
import cn.com.liveuc.privilege.model.Role;
import cn.com.liveuc.privilege.model.User;
/**
 * @說明   自定義權限標籤
*/
public class PerssionTag extends SimpleTagSupport {

  //自定義標籤屬性,用於標籤傳入參數
  private String uri;

  //接收標籤傳入的參數
  public void setUri(String uri) {
    this.uri = uri;
  }
  @Override
  public void doTag() throws JspException, IOException {
    //獲取用戶登陸後保存的 Session
    PageContext page = (PageContext) this.getJspContext();
    User user = (User) page.getSession().getAttribute("login");
    //如果用戶登陸
    if(user != null) {
      //用戶登陸判斷用戶權限
      List<String> list = new ArrayList<String>();
      //獲取用戶的角色
      Set<Role> role = user.getRole();
      for(Role r:role) {
        //獲取角色對應的權限
        Set<Privilege> privilege = r.getPrivilege();
        for(Privilege p:privilege) {
          //獲取權限對應的資源
          Set<Resource> res = p.getResource();
          for(Resource re:res) {
            list.add(re.getUri());
          }
        }
      }
      for(String ur:list) {
        //判斷用戶的權限
        if(ur.equals(uri)) {
          this.getJspBody().invoke(null); //有權限輸出標籤體內容
        }
      }
    }
  }
}

兩個關鍵點:屬性通過 setter 注入(方法名 setXxx 對應標籤屬性 xxx);是否渲染由 getJspBody().invoke(null) 決定——調用了就輸出標籤體,不調用就什麼也不輸出。

二、編寫 TLD 描述文件

在 WEB-INF 下新建 tld 文件(例如 wxt.tld):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<taglib xmlns="https://java.sun.com/xml/ns/j2ee" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
  version="2.0"
  xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
  <description><![CDATA["To make it easier to access dynamic data;
                   the Apache Struts framework includes a library of custom tags.
                   The tags interact with the framework's validation and internationalization features;
                   to ensure that input is correct and output is localized.
                   The Struts Tags can be used with JSP FreeMarker or Velocity."]]></description>
  <display-name>"Struts Tags"</display-name>
  <tlib-version>2.2.3</tlib-version>
  <short-name>s</short-name>
  <uri>/wxt</uri>
  <tag>
    <name>per</name><!-- 標簽名 -->
    <tag-class>cn.com.liveuc.privilege.tag.PerssionTag</tag-class>
    <body-content>scriptless</body-content>
    <!-- 標簽屬性 -->
    <attribute>
      <name>uri</name><!-- 屬性名稱 -->
      <required>true</required><!-- 是否必須 -->
      <rtexprvalue>true</rtexprvalue><!-- 是否支持 EL 表達式 -->
    </attribute>
  </tag>
</taglib>

其中 uri 決定標籤前綴如何在頁面中引用,body-content 為 scriptless 表示標籤體只能包含模板文本與 EL,不能寫腳片段,rtexprvalue 為 true 才允許用 ${} 動態傳值。

三、在 JSP 中使用

導入標籤:

<%@taglib prefix="wxt" uri="/wxt" %>

使用標籤:

<wxt:per uri="${pageContext.request.contextPath }/user/list">
      <a href="${pageContext.request.contextPath }/user/list" target="reight">用戶管理</a>
</wxt:per>

用戶權限包含該 uri 資源時,鏈接才會渲染出來。

四、實戰提醒

  • 標籤只負責展示層控制,不能替代接口權限校驗。隱藏按鈕不等於接口安全,服務端必須再判一次。
  • 權限集合建議加緩存。示例中每次渲染都遍歷「用戶→角色→權限→資源」多層集合,頁面上十幾個標籤就會重複計算十幾次,可把結果放入 request 屬性或本地緩存。
  • 提供反向標籤更好用。再寫一個 <wxt:notper>,內部用 flag 記錄是否已匹配,未匹配時輸出「無權限」提示,頁面邏輯會清晰很多。
  • 注意標籤類命名。示例中的 PerssionTag 拼寫有誤(應為 PermissionTag),上線前建議修正,避免長期沿用。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved