Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using JSTL forEach the array prints the String.toString() and not actual string value

Tags:

java

jsp

jstl

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?

like image 741
Ruepen Avatar asked Dec 19 '11 16:12

Ruepen


2 Answers

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.

See also:

  • Our EL tag wiki page

Unrelated to the concrete problem, table headers needs to be represented in HTML by <th>, not <td>.

like image 88
BalusC Avatar answered Sep 28 '22 03:09

BalusC


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>
like image 39
Sagar Sane Avatar answered Sep 28 '22 02:09

Sagar Sane