【问题标题】:How to create an iteration tag handler that define a variable如何创建定义变量的迭代标记处理程序
【发布时间】:2019-01-23 00:57:28
【问题描述】:

问题

我正在尝试创建一个自定义标记处理程序,其目的是遍历给定列表并将项目与给定分隔符连接起来。标签的签名是:<custom:joinList list="${product.vendors}" delimiter=", " var="vendor">。一些笔记。 list 属性应该是 Collection.class 对象。 delimiter 始终是 Stringvar 是主体可以在每个循环中访问的变量。所以标签应该总是有一个正文来打印每个项目,然后标签处理程序会在末尾附加delimiter

例如,这就是从 JSP 调用标签的方法:

<custom:joinList list="${product.vendors}" delimiter=", " var="vendor">
    ${vendor.id} // Vendor obviously has a getId() method
</custom:joinList>

我的尝试

首先,我创建了一个扩展 javax.servlet.jsp.tagext.SimpleTagSupport 的类,并在 doTag() 方法中将列表中的下一项作为属性传递给 pageContext

其次,我尝试扩展 javax.servlet.jsp.tagext.TagSupport,但我不知道如何在每次执行主体后写入 out 编写器。

代码示例

定义标签的 TLD:

<tag>
    <description>Joins a Collection with the given delimiter param</description>
    <name>joinList</name>
    <tag-class>com.myproject.tags.JoinListTag</tag-class>
    <body-content>tagdependent</body-content>
    <attribute>
        <description>The collection to be printed</description>
        <name>list</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>The delimiter that is going to be used</description>
        <name>delimiter</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <description>The item that will return on each loop to get a handle on each iteration</description>
        <name>var</name>
        <required>true</required>
    </attribute>
</tag>

这是自定义标签处理程序,我想这很简单。

public class JoinListTag extends SimpleTagSupport {

    private Iterator iterator;
    private String delimiter;
    private String var;

    public void setList(Collection list) {
        if (list.size() > 0) {
            this.iterator = list.iterator();
        }
    }

    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }

    public void setVar(String var) {
        this.var = var;
    }

    @Override
    public void doTag() throws JspException, IOException {
        if (iterator == null) {
            return;
        }

        while (iterator.hasNext()) {
            getJspContext().setAttribute(var, iterator.next()); // define the variable to the body
            getJspBody().invoke(null); // invoke the body

            if (iterator.hasNext()) {
                getJspContext().getOut().print(delimiter); // apply the delimiter
            }
        }
    }
}

如果product.vendors 列表是这样填充的,我希望打印1, 2, 3,但我得到的是${vendor.id}, ${vendor.id}, ${vendor.id}

【问题讨论】:

    标签: jsp jsp-tags


    【解决方案1】:

    所以最终只换了一个词。

    在我的 TLD 中,我将标签的 body-content 定义为 tagdependent。我不得不将其更改为scriptless。显然再次浏览文档不会伤害任何人......

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多