Creating a List in EL
Asked Answered
C

4

8

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?

Compote answered 14/9, 2009 at 12:2 Comment(0)
C
3

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

Cornaceous answered 19/5, 2021 at 12:56 Comment(0)
S
8

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.

Skerrick answered 14/9, 2009 at 12:57 Comment(2)
is this still true 4 years later: "neither EL nor JSTL provide a built-in mechanism for adding items to a collection". Couldn't find a way to do thisRiha
@Riha - I haven't used EL heavily for several years, but I see no reason for it to change. JSP is intended as a view technology, and mutation is something that a controller should do.Skerrick
C
3

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.

Chesnut answered 14/9, 2009 at 17:47 Comment(1)
EL has new features since 2009: see also this answer.Chesnut
F
3

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

Formate answered 20/1, 2013 at 19:51 Comment(0)
C
3

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

Cornaceous answered 19/5, 2021 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.