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

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 ​​are printed:

 org.apache.commons.el.ImplicitObjects$7@6ac86ac8 org.apache.commons.el.ImplicitObjects$7@6ac86ac8 ... 

It seems to me that the memory value is printed, not the value contained in each line. What am I missing here?

+7
source share
2 answers

You are incorrectly referring to the value of items . Taglibs / EL and scriptlets do not use the same variable scope. You basically print columnHeaders.toString() in the items attribute and say c:forEach to iterate over it. Instead, you need to put it in the request area (preferably a servlet) and use EL ${} usual 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> 

In addition, ${header} is a reserved EL variable related to the request header map (see implicit objects in EL ), you would need to rename it to another one, for example ${columnHeader} in the example above.

See also:


Unrelated to a specific problem, table headers should be represented in HTML <th> , not <td> .

+14
source

This thread is quite old, but thought it would be useful nonetheless.

If you are not required to use String[] , you can use Collection<String> or List<String> .

If you do this, you do not have to put the variable in the request area.

For example, 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> 
+2
source

All Articles