I thought <%= %>
is supposed to evaluate to a string when used in the context of JSTL1. But this does not seem to be the case in the code below:
<c:forEach var="item" items="<%= new Object[] { 1, 2, 3 } %>">
Item: ${item}
</c:forEach>
To my surprise, the <c:forEach>
tag actually iterates over the array inside the scriptlet:
Item: 1
Item: 2
Item: 3
Can someone please explain this behavior?
Thanks!
Answering my own question after some reading.
In short, I was wrong about how JSP tag attributes are evaluated. If a scriptlet is used to set the value of an attribute1, its return value, rather than being converted to a string, is used directly to set the value of the attribute. (If the types don't match, EL performs type coercion to try and make it work. If that fails, an exception is raised.)
In the example
the type of the tag's
items
attribute isObject
, so the attribute is set to the result of the scriptlet—the arraynew Object[] { 1, 2, 3 }
.<c:forEach items="abc<%= "def" %>" var="c">
will execute the scriptlet and evaluate to the stringabcdef
. But instead, it will set the attribute value ofitems
to just the stringabc<%= "def" %>
.