Search code examples
javajspjsp-tagstaglib

Taglib in Java: tag with array parameter


How can I define a tag that receives a array as a parameter?

Thanks


Solution

  • JSTL does it, and you can too.

    I happen to have an el function example handy, and then I'll paste a portion of the c:forEach definition to give you an idea:

    You could pass it as a delimited string, but if you want a collection or array, you can use something like this:

    <function>
      <name>join</name>
      <function-class>mypackage.Functions</function-class>
      <function-signature>String join(java.lang.Object, java.lang.String)</function-signature>
    </function>
    

    and

    /**
     * jstl's fn:join only works with String[].  This one is more general.
     * 
     * usage: ${nc:join(values, ", ")}
     */
    public static String join(Object values, String seperator)
    {
        if (values == null)
            return null;
        if (values instanceof Collection<?>)
            return StringUtils.join((Collection<?>) values, seperator);
        else if (values instanceof Object[])
            return StringUtils.join((Object[]) values, seperator);
        else
            return values.toString();
    }
    

    Obviously, instead of an Object input you can use an array if you don't want to handle collections as well.

    Here is the c:forEach definition:

    <tag>
        <description>
            The basic iteration tag, accepting many different
            collection types and supporting subsetting and other
            functionality
        </description>
        <name>forEach</name>
        <tag-class>org.apache.taglibs.standard.tag.rt.core.ForEachTag</tag-class>
        <tei-class>org.apache.taglibs.standard.tei.ForEachTEI</tei-class>
        <body-content>JSP</body-content>
        <attribute>
            <description>
                Collection of items to iterate over.
            </description>
            <name>items</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.Object</type>
        </attribute>
        ...