How does a scriptlet pass an array to a JSTL tag?

2019-08-12 06:18发布

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!

References

  1. test attribute in JSTL <c:if> tag

1条回答
地球回转人心会变
2楼-- · 2019-08-12 07:02

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

<c:forEach var="item" items="<%= new Object[] { 1, 2, 3 } %>">

the type of the tag's items attribute is Object, so the attribute is set to the result of the scriptlet—the array new Object[] { 1, 2, 3 }.

  1. Note that you can't use a scriptlet in combination with literal string to set an attribute. That is, you might think <c:forEach items="abc<%= "def" %>" var="c"> will execute the scriptlet and evaluate to the string abcdef. But instead, it will set the attribute value of items to just the string abc<%= "def" %>.
查看更多
登录 后发表回答