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

I have a list that contains some objects. Objects have a hours field.

In <c:foreach> I repeat the list and retrieve the objects.

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

My code is:

 <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 tried to do this, but it gave me the following error:

 javax.el.ELException: Failed to parse the expression [${attendance.Hours += attendance.Hours } 
+6
source share
1 answer

In Java, it will look like this:

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

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> 
+20
source

Source: https://habr.com/ru/post/921742/