简体   繁体   中英

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

<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()%>

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM