標準 `web.xml` 安全約束僅能保護**整個 URL**,無法精細到「按鈕、欄位、區塊」級別。結合**自訂標籤庫 + 外部 XML 權限配置**,可在 JSP 中宣告式控制任意片段顯示,業務邏輯零侵入。
JSP 頁面 XML 配置 (permission.xml) 標籤處理器
┌──────────────┐ ┌─────────────────────────┐ ┌──────────────────┐
│ <cust:auth │ 讀取 │ <element name="btnDel"> │ 比對 │ JspAuthTag │
│ element="btnDel"> ─────→ │ <role name="admin"/> │ ─────────→ │ doAfterBody() │
│ 按鈕內容 │ │ </element> │ 當前用戶 │ 若有權限 → 輸出 │
│ </cust:auth> │ │ <element name="btnAdd"> │ 角色集合 │ 無權限 → 跳過 │
└──────────────┘ │ <role name="mgr"/> │ └──────────────────┘
│ <role name="admin"/> │
│ </element> │
└─────────────────────────┘
<?xml version="1.0" encoding="UTF-8"?>
<permissions>
<element name="btnDeleteUser">
<role name="ROLE_ADMIN" />
</element>
<element name="btnExportReport">
<role name="ROLE_MANAGER" />
<role name="ROLE_ADMIN" />
</element>
<element name="panelSalary">
<role name="ROLE_HR" />
<role name="ROLE_ADMIN" />
</element>
</permissions>
package com.example.tag;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
public class JspAuthTag extends BodyTagSupport {
private static final String CONFIG_PATH = "/WEB-INF/permission.xml";
private static volatile Map<String, Set<String>> permCache; // element → roles
private String element; // 必填屬性
public void setElement(String element) { this.element = element; }
@Override
public int doAfterBody() throws JspException {
// 1. 懶加載並快取權限映射
if (permCache == null) {
synchronized (JspAuthTag.class) {
if (permCache == null) loadPermissions();
}
}
// 2. 取得當前用戶角色 (假設存放在 session)
HttpSession session = pageContext.getSession();
Collection<String> userRoles = (Collection<String>) (session != null ? session.getAttribute("userRoles") : Collections.emptyList());
// 3. 權限判斷
Set<String> allowedRoles = permCache.get(element);
boolean authorized = allowedRoles != null && !Collections.disjoint(userRoles, allowedRoles);
// 4. 輸出或跳過標籤體
if (authorized) {
try {
BodyContent body = getBodyContent();
if (body != null) body.writeOut(getPreviousOut());
} catch (IOException e) {
throw new JspException("輸出標籤體失敗", e);
}
}
return SKIP_BODY; // 體內容已手動處理或跳過
}
private void loadPermissions() {
Map<String, Set<String>> map = new HashMap<>();
try {
InputStream is = pageContext.getServletContext().getResourceAsStream(CONFIG_PATH);
if (is == null) throw new FileNotFoundException(CONFIG_PATH);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
NodeList elements = doc.getElementsByTagName("element");
for (int i = 0; i < elements.getLength(); i++) {
Element el = (Element) elements.item(i);
String name = el.getAttribute("name");
Set<String> roles = new HashSet<>();
NodeList roleNodes = el.getElementsByTagName("role");
for (int j = 0; j < roleNodes.getLength(); j++) {
roles.add(((Element) roleNodes.item(j)).getAttribute("name"));
}
map.put(name, roles);
}
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new RuntimeException("載入權限配置失敗", e);
}
permCache = Collections.unmodifiableMap(map);
}
// 熱重載支援 (開發模式)
public static void reload() { permCache = null; }
}
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://java.sun.com/xml/ns/javaee" version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>auth</short-name>
<uri>https://example.com/tags/auth</uri>
<tag>
<name>auth</name>
<tag-class>com.example.tag.JspAuthTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>element</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue> <!-- 支援 EL 表達式動態指定 -->
</attribute>
</tag>
</taglib>
<%@ taglib prefix="auth" uri="https://example.com/tags/auth" %>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<table>
<c:forEach items="${userList}" var="u">
<tr>
<td>${u.name}</td>
<td>${u.email}</td>
<td>
<auth:auth element="btnDeleteUser">
<button onclick="del('${u.id}')">刪除</button>
</auth:auth>
<auth:auth element="btnExportReport">
<button onclick="export('${u.id}')">導出</button>
</auth:auth>
</td>
</tr>
</c:forEach>
</table>
<auth:auth element="panelSalary">
<div class="salary-panel">...薪資明細內容...</div>
</auth:auth>
// LoginController
List<String> roles = roleService.findRolesByUser(userId); // 從 DB/緩存讀取
session.setAttribute("userRoles", roles); // 標籤直接讀取此屬性
「標籤庫 + XML」模式實現了**頁面元素級權限的宣告式控制**,將「誰能看見什麼」從 Java 代碼剝離到配置文件,符合**關注點分離**原則,極大降低維護成本,是傳統 JSP 專案權限精細化的最佳實踐。