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

我怕爱的太早我们不能终老 提交于 2019-12-11 08:08:11

问题


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:


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" %>.


来源:https://stackoverflow.com/questions/27684162/how-does-a-scriptlet-pass-an-array-to-a-jstl-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!