简体   繁体   English

为什么 forEach var 不能作为参数工作? JSP/JSTL

[英]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() .我的 arraylist (List) 和 forEach 都有效,但我不明白为什么 var i无法作为 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.但是,如果我像${i}一样使用它,它也可以工作,如果我想打印${List.get(0).getName()}发送一个数字作为参数,它也可以工作。

So my question is why "i" doesn't work when is used as a parameter to get the list that I want.所以我的问题是为什么“i”在用作参数来获取我想要的列表时不起作用。

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").您期望在这些地方编写 java 代码,但是 JSP 期望这些表达式遵循表达式语言(“EL”)的语法。

In EL, array/List/Map elements are accessed using brackets .在 EL 中,使用括号访问数组/列表/映射元素。 Properties are expected to follow the naming convention of getters, so .name will internally be translated to getName() .属性应遵循 getter 的命名约定,因此.name将在内部转换为getName()

Overall, your expression should be总的来说,你的表达应该是

List[i].name

which EL evaluates one by one, eventually returning the same as List.get(i).getName() . EL 一一评估,最终返回与List.get(i).getName()相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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