views:

31

answers:

2

Hi,

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

Thanks

A: 

If the array data is Strings, you could pass the values as a delimited list, maybe in an attribute.

<mytag myattribute="value1,value2,value3"/>

You could do the same with the tag body, or a jsp:param or some such, but I suspect that the attribute approach is probably easiest to code and understand.

Brabster
Can't think of another way off the top of my head. Tags are supposed to be used declaratively, in JSP pages, so all you have is really XML, i.e. strings, tags, attributes unless you're going to use scriptlets, which isn't good practise. Can you elaborate on exactly what you're trying to do?
Brabster
+1  A: 

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>
    ...
Peter DeWeese
This solution may work, but I have already done using params and add this params to the parent tag.
Victor