artbristol
artbristol

Reputation: 32407

Creating a List in EL

Suppose I have a custom tag that takes a List of Strings:

<%@ attribute name="thelist" type="java.util.List&lt;java.lang.String&gt;"
    required="true" %>

How can I create this attribute in the jsp that calls the tag? I could use a scriptlet

<tags:list thelist='<%= java.util.Arrays.asList("blah","blah2") %>' />

but is there any way to do this using Expression Language, since that seems to be preferred?

Upvotes: 8

Views: 15532

Answers (4)

Jasper de Vries
Jasper de Vries

Reputation: 20198

Since EL 3 you can simply do #{['blah','blah2']} to create a list.

Upvotes: 3

alexfdz
alexfdz

Reputation: 435

If you want to avoid scriptlet or ugly EL functions, you could use you own builder and fool the EL interpreter:

...

<jsp:useBean id="listBuilder" class="com.example.ELListBuilder"/>

<ul>
  <c:forEach var="item" items="${listBuilder['red']['yellow']['green'].build}">
      <li>${item}</li>
  </c:forEach>
</ul>

...

Check the example here: https://gist.github.com/4581179

Upvotes: 3

McDowell
McDowell

Reputation: 108899

As kdgregory says, you could do this with custom tag library functions, though it won't be pretty. For example, something like this:

#{foo:add(foo:add(foo:add(foo:newList(), 'One'), 'Two'), 'Three')}

You are merely running into the limitations of what used to be called the Simplest Possible Expression Language.

It would be easier to do this via some other mechanism, like a bean.

Upvotes: 3

kdgregory
kdgregory

Reputation: 39606

If all you want to do is create the list, then you can use [<jsp:useBean>][1] to create the object in the desired scope:

<jsp:useBean id="thelist" scope="request" class="java.util.ArrayList" />

This works because ArrayList has a no-args constructor. However, the list won't have anything in it. And, as far as I know, neither EL nor JSTL provide a built-in mechanism for adding items to a collection -- they're both focused on read-only access. I suppose that you could define an EL function mapping to enable the add() method.

However, I think that you're better off not trying to force JSP to do something that it doesn't want to do. In this case, that means that rather than use a JSP tagfile, you should write an actual tag handler in Java.

Upvotes: 8

Related Questions