Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jsp

jstl

el

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 }
like image 718
Sanjay Verma Avatar asked Jul 31 '12 07:07

Sanjay Verma


1 Answers

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>
like image 147
JB Nizet Avatar answered Nov 01 '22 11:11

JB Nizet