gpt4 book ai didi

java - 使用 jSTL 从子自定义标签访问父自定义标签属性结果

转载 作者:行者123 更新时间:2023-11-30 04:25:25 24 4
gpt4 key购买 nike

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

<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)的结果,以根据返回值显示输出判断条件是否正确。

谢谢,开发人员。

最佳答案

我在研究类似问题时遇到了这个问题。为了后代的利益,以下是我在野外看到的实现方式。我假设您的标签已在标签库描述 rune 件中正确定义。

父标签类

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
}

<a href="http://docs.oracle.com/javaee/7/api/javax/servlet/jsp/tagext/BodyTagSupport.html#doStartTag%28%29" rel="noreferrer noopener nofollow">doStartTag</a>在我们开始处理标签内的正文之前调用,我们知道我们可以安全地访问子标签中我们关心的属性。

子标签

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
}
}

使用<a href="http://docs.oracle.com/javaee/7/api/javax/servlet/jsp/tagext/TagSupport.html#getParent%28%29" rel="noreferrer noopener nofollow">getParent()</a>的原因这里不鼓励的是它只检索最接近的封闭标签。如果我们需要重构代码,这会限制我们。

<test test1="foo" test2="bar" test3="foobar">
<c:if test="${ condition }">
<result1/>
</c:if>
<result2/>
<result3/>
</test>
  • 通过 getParent() 实现,我们无法检索父标记,因为我们插入的 JSTL 标记现在是最接近的封闭标记。
  • 通过 findAncestorWithClass() 实现,我们成功检索父标记,因为我们迭代地搜索具有指定类的祖先标记。

关于java - 使用 jSTL 从子自定义标签访问父自定义标签属性结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16008328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com