Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to iteration variable in c:forEach with a scriptlet/expression?

var is a static attribute to expose the current element (local to the body)

How to acces to var attribute through scriptlet/expression?

Initialization code

<% 
Employee e = new Employee();
e.setName("name");
e.setEmail("[email protected]");
java.util.List<Employee> empList = new java.util.ArrayList();
empList.add(e);
request.setAttribute("empList", empList); %>

forEach code 1 deferredExpression Error

<c:forEach var="emp" items="${employees}">
  <c:out value="${emp.name}"/><br><%=emp.getName()%> 
</c:forEach>

NOR

forEach code 2 deferredExpression Error

<c:forEach var="emp" items="${empList}" varStatus="status">
  Emp email: <%= ((Employee)(pageContext.findAttribute("emp"))).getName() %>
</c:forEach>
like image 991
Joe Avatar asked Oct 22 '13 21:10

Joe


2 Answers

I had java.lang.NoSuchFieldError: deferredExpression every time I change because of I had different versions of JSTL libraries, and now I only leave one jstl-1.2.jar more info about JSTL.

The JSTL documentation documentation says it clearly "Name of the exported scoped variable for the current item of the iteration. This scoped variable has nested visibility." and nested means from the start tag until the end tag .

EL code

<c:forEach begin="0" end="5" var="countvar">
Iteration number ${ countvar + 24 }
</c:forEach>

Alternative JSP scripting

<c:forEach begin="0" end="5" var="countvar">
Iteration number
<%= ((Integer) (pageContext.findAttribute("cv")).intValue()+24 %>
</c:forEach>

Another c:forEach example with a collection

<% 
 Employee e = new Employee();
 e.setName("name");
 e.setEmail("[email protected]");
 java.util.List<Employee> empList = new java.util.ArrayList();
 empList.add(e);
 request.setAttribute("empList", empList); 
%>

<c:forEach var="emp" items="${empList}" varStatus="status">
  Emp email: <%= ((Employee)(pageContext.findAttribute("emp"))).getName() %>
</c:forEach>
like image 126
Joe Avatar answered Sep 27 '22 01:09

Joe


I use following general snippet:

<c:forEach items="<%= itemList %>" var="item">
    <%
        ItemClass item = (ItemClass)pageContext.getAttribute("item");
    %>
    <p>Value with scriptlet: <%= item.getValue() %></p>
    <p>Value with EL ${item.value}</p>
</c:forEach>

Your case with EL:

<c:forEach var="emp" items="<%= empList %>" varStatus="status">
  ${emp.name} email: ${emp.email}
</c:forEach>

Your case with scriptlet:

<c:forEach var="emp" items="<%= empList %>" varStatus="status">
  <%
      Employee employee = (Employee)pageContext.getAttribute("emp");
  %>
  <%= employee.getName() %> email: <%= employee.getEmail() %>
</c:forEach>
like image 42
Pawel Kruszewski Avatar answered Sep 26 '22 01:09

Pawel Kruszewski