1

次の構造のカスタムタグを作成しています

<test test1="" test2="" test3="">
  <result1>result of the test1 condition</result1>
  <result2>result of the test2 condition</result2>
  <result3>result of the test3 condition</result3>
</test>

そこで、子タグresult1、result2、result3の親タグ属性test1、test2、test3の結果(これらの属性の戻り値はtrue/false)にアクセスし、条件の戻り値に基づいて出力を表示したいそれが真か偽か。

ありがとう、開発者。

4

1 に答える 1

2

同様の問題を調査しているときに、この質問に出くわしました。後世のために、これが実際にどのように達成されたかを以下に示します。タグ ライブラリ記述子ファイルでタグが適切に定義されていると仮定します。

親タグ クラス

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() 実装では、指定されたクラスの先祖タグを繰り返し検索するため、親タグを正常に取得できます。
于 2014-01-15T02:52:53.890 に答える