使用jstl从子自定义标记访问父自定义标记属性结果

时间:2013-04-15 05:43:16

标签: java jsp jstl

正在创建以下结构的自定义标签

<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)的结果,以显示基于返回值的输出无论是真还是假的条件。

谢谢, 显影剂。

1 个答案:

答案 0 :(得分: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()实现,我们成功检索了父标记,因为我们迭代搜索具有指定类的祖先标记。