Suppose I have a custom tag that takes a List of Strings:
<%@ attribute name="thelist" type="java.util.List<java.lang.String>"
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?
The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component, and other objects like request, session, application etc. There are many implicit objects, operators and reserve words in EL. It is the newly added feature in JSP technology version 2.0.
JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean values, and null.
In the expression ${2 * 2} , the ${} is JSP syntax for interpolating code into HTML.
JSP EL Implicit Objects It is used to access the value of any variable which is set in the Request scope.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With