Home > Enterprise >  Why forEach var doesn't work as a parameter? JSP/JSTL
Why forEach var doesn't work as a parameter? JSP/JSTL

Time:08-24

<c:forEach var = "i" begin = "0" end = "${List.size()}">
  <option value="2" selected>
    ${List.get(i).getName()}
  </option>
</c:forEach>

My arraylist (List) works and also the forEach, but I don't understand why the var i is not able to reach as a parameter for the function get(). But if I use it like ${i} it works, also if I want to print ${List.get(0).getName()} sending a number as a paramether it works.

So my question is why "i" doesn't work when is used as a parameter to get the list that I want.

I also tried these:

<c:out value="${List.get(i).getName()}"/>

<%=List.get(i).getName()%>

CodePudding user response:

The problem here is the syntax. You expect to write java code in these places, however JSP expects these expression to follow the syntax of the Expression Language ("EL").

In EL, array/List/Map elements are accessed using brackets. Properties are expected to follow the naming convention of getters, so .name will internally be translated to getName().

Overall, your expression should be

List[i].name

which EL evaluates one by one, eventually returning the same as List.get(i).getName().

  • Related