同様の問題を調査しているときに、この質問に出くわしました。後世のために、これが実際にどのように達成されたかを以下に示します。タグ ライブラリ記述子ファイルでタグが適切に定義されていると仮定します。
親タグ クラス
public class TestTag extends BodyTagSupport {
// Attributes
private String test1;
private String test2;
private String test3;
// Setters
public void setTest1(String str) {
this.test1 = str;
}
// Et Cetera
// Accessors
public String getTest1() {
return this.test1;
}
// Et Cetera
@Override
public int doStartTag() {
// Do whatever is necessary here to set values for your attributes
}
// Process body
}
タグ内のボディの処理を開始する前に が呼び出されるためdoStartTag
、子タグで関心のある属性に安全にアクセスできることがわかります。
子タグ
public class Result1Tag extends TagSupport {
// Take care of declaring and setting attributes if necessary
@Override
public int doStartTag() throws JspException {
//TestTag parent = (TestTag)super.getParent(); Not recommended
TestTag parent = (TestTag)TagSupport.findAncestorWithClass(this, TestTag.class);
if (parent == null) {
throw new JspTagException("Result1Tag must be enclosed in a TestTag");
}
String test1 = parent.getTest1();
// Whatever logic you need for this attribute to generate content
}
}
ここで の使用が推奨されない理由はgetParent()
、最も近い囲みタグのみを取得するためです。コードをリファクタリングする必要がある場合、これは私たちを制限します。
<test test1="foo" test2="bar" test3="foobar">
<c:if test="${ condition }">
<result1/>
</c:if>
<result2/>
<result3/>
</test>
- getParent() 実装では、挿入した JSTL タグが最も近い囲みタグになっているため、親タグの取得に失敗します。
- findAncestorWithClass() 実装では、指定されたクラスの先祖タグを繰り返し検索するため、親タグを正常に取得できます。