子標籤透過 getParent() 取得父標籤,或用 findAncestorWithClass(this, ParentTag.class) 遞迴尋找指定祖先標籤,進而存取其屬性與方法。
利用 Apache Commons BeanUtils PropertyUtils.getProperty(obj, propName) 動態讀取物件屬性,無需寫死 Getter。需將 commons-beanutils.jar 放入 WEB-INF/lib。
目標結構:
<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 指定屬性,輸出至頁面。
body-content>JSP</body-content> 允許 Body 內容。body-content>empty</body-content>。