Search code examples
javajspjstlel

How to update value in <c:set> tag using EL inside a <c:foreach> tag


I have list which contains some objects in it. The objects have an hours field.

In the <c:foreach> I am iterating the list and fetching the objects.

Now I want to sum up the hours field of all the iterated objects in a totalHours variable.

My code:

<c:forEach var="attendance" items="${list }" varStatus="rowCounter1">
  <tr>
    <td><c:out value="${rowCounter1.count}"></c:out></td>
    <td><c:out value="${attendance.date }"></c:out></td>
    <td><c:out value="${attendance.inTime }"></c:out></td>
    <td><c:out value="${attendance.outTime }"></c:out></td>
    <td><c:out value="${attendance.interval }"></c:out></td>

    <c:set var="totalHours" value="${attendance.Hours += attendance.Hours }"
           target="${attendance}"</c:set>                                       
  </tr>
</c:forEach>

I was trying this, but it gave me the following error:

javax.el.ELException: Failed to parse the expression [${attendance.Hours += attendance.Hours }

Solution

  • In Java, it would look like this:

    // before the loop:
    int totalHours = 0;
    for (Attendance attendance : list) {
        totalHours = totalHours + attendance.getHours();
    }
    

    So do the same in JSTL:

    <c:set var="totalHours" value="${0}"/>
    <c:forEach var="attendance" items="${list }" varStatus="rowCounter1">
        ...
        <c:set var="totalHours" value="${totalHours + attendance.hours}"/>
    </c:forEach>