I have the following code:
String[] columnHeaders = {"Banana", "Apple", "Carrot", "Orange", "Lychee", "Permisson"};
<c:forEach var="header" items="<%= columnHeaders%>">
<td>
<c:out value="${header}" />
</td>
</c:forEach>
When the JSP is executed, the following values get printed:
org.apache.commons.el.ImplicitObjects$7@6ac86ac8
org.apache.commons.el.ImplicitObjects$7@6ac86ac8
...
It appears to me that the memory value is being printed and not the value contained in each string. What am I missing here?
You're referencing the items
value incorrectly. Taglibs/EL and scriptlets does not share the same variable scope. You're basically printing columnHeaders.toString()
in the items
attribute and telling c:forEach
to iterate over it. Instead, you need to put it in the request scope (preferably by a servlet) and use EL ${}
the normal way:
<%
String[] columnHeaders = {"Banana", "Apple", "Carrot", "Orange", "Lychee", "Permisson"};
request.setAttribute("columnHeaders", columnHeaders);
%>
<c:forEach var="columnHeader" items="${columnHeaders}">
<td>
<c:out value="${columnHeader}" />
</td>
</c:forEach>
Also, ${header}
is an reserved EL variable referring to the request header map (see implicit objects in EL), you'd need to rename it to something else such as ${columnHeader}
in the above example.
Unrelated to the concrete problem, table headers needs to be represented in HTML by <th>
, not <td>
.
This thread is pretty old but thought it would be useful nonetheless.
If you are not obligated to use String[]
, you could use Collection<String>
or List<String>
.
If you do that, you won't have to put a variable in the request scope.
For example, something like the following should work:
List<String> columnHeaders = Arrays.asList("Banana", "Apple", "Carrot", "Orange", "Lychee", "Permisson");
<c:forEach var="columnHeader" items="${columnHeaders}">
<td>
<c:out value="${columnHeader}" />
</td>
</c:forEach>
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