JSP自定義標簽能將業務邏輯與頁面展示分離,實現可復用的視圖組件。本文以權限控制標簽<wxt:per>為例,完整演示:標簽處理類開發、TLD描述符配置、JSP頁面引用、項目結構組織,適用於Java EE / Jakarta EE 環境。
<wxt:per uri="${pageContext.request.contextPath}/privilege/list">
<a href="${pageContext.request.contextPath}/privilege/list" target="right">權限管理</a>
</wxt:per>
package cn.com.liveuc.privilege.tag;
import java.io.IOException;
import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import cn.com.liveuc.privilege.model.*;
public class PerssionTag extends SimpleTagSupport {
private String uri; // 標簽屬性
public void setUri(String uri) { this.uri = uri; }
@Override
public void doTag() throws JspException, IOException {
PageContext page = (PageContext) getJspContext();
User user = (User) page.getSession().getAttribute("login");
if (user != null) {
// 收集用戶所有權限 URI
Set permittedUris = new HashSet<>();
for (Role role : user.getRole()) {
for (Privilege priv : role.getPrivilege()) {
for (Resource res : priv.getResource()) {
permittedUris.add(res.getUri());
}
}
}
// 權限匹配:輸出標簽體內容
if (permittedUris.contains(uri)) {
getJspBody().invoke(null); // 關鍵:輸出標簽體
}
}
// 無權限/未登錄:不輸出任何內容
}
}
WEB-INF/tlds/wxt.tld)<?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>wxt</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>
<%@ taglib prefix="wxt" uri="/wxt" %>
<wxt:per uri="${pageContext.request.contextPath}/user/list">
<a href="${pageContext.request.contextPath}/user/list" target="right">用戶管理</a>
</wxt:per>
<wxt:per uri="${pageContext.request.contextPath}/role/list">
<a href="${pageContext.request.contextPath}/role/list" target="right">角色管理</a>
</wxt:per>
| 基類 | 適用場景 | 關鍵方法 | 特點 |
|---|---|---|---|
TagSupport | 無標簽體/簡單標簽 | doStartTag(), doEndTag() | 經典體系,返回SKIP_BODY/EVAL_PAGE |
BodyTagSupport | 需操作標簽體內容 | doInitBody(), doAfterBody() | 可多次迭代標簽體 |
SimpleTagSupport | JSP 2.0+ 推薦,簡化模型 | doTag() | 無迭代,getJspBody().invoke()輸出體 |
<function>,頁面直接${wxt:hasPerm(uri)}.tag文件純JSP實現,無需Java類validate()方法,頁面編譯期報錯findAncestorWithClass(this, ParentTag.class)<sec:authorize access="hasRole('ADMIN')">v-if/ngIfsrc/
└─ main/
├─ java/cn/com/liveuc/privilege/tag/PerssionTag.java
└─ webapp/
├─ WEB-INF/tlds/wxt.tld
└─ jsp/privilege/list.jsp