首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

Taglib 進階:巢狀標籤與屬性反射存取

     編輯:關於JSP

巢狀標籤通訊機制

子標籤透過 getParent() 取得父標籤,或用 findAncestorWithClass(this, ParentTag.class) 遞迴尋找指定祖先標籤,進而存取其屬性與方法。

屬性反射存取

利用 Apache Commons BeanUtils PropertyUtils.getProperty(obj, propName) 動態讀取物件屬性,無需寫死 Getter。需將 commons-beanutils.jar 放入 WEB-INF/lib。

實作案例:WithTag + OutputTag

目標結構:

<diego:with object="${Man}">
  <diego:output property="name"/>
</diego:with>

WithTag (父):解析 EL 取得物件,存在 value 欄位,doStartTag 返回 EVAL_BODY_INCLUDE 執行 Body。

public class WithTag extends BodyTagSupport {
    private Object value, output;
    public void setValue(Object value) throws JspException {
        this.value = ExpressionEvaluatorManager.evaluate(...);
    }
    public Object getValue() { return value; }
    public void setOutput(Object output) { this.output = output; }
    public int doStartTag() { return EVAL_BODY_INCLUDE; }
    public int doEndTag() throws JspException {
        pageContext.getOut().print(output);
        return EVAL_PAGE;
    }
}

OutputTag (子):doStartTag 中尋找 WithTag,取得 value 物件,用 PropertyUtils 讀取 property 指定屬性,輸出至頁面。

TLD 宣告重點

  • 父標籤 body-content>JSP</body-content> 允許 Body 內容。
  • 子標籤 body-content>empty</body-content>。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved