Question

I am having a slight issue in my JSP page. I am attempting to loop through a collection of items, and doing a compare to make sure the current value I am looking at is not the same as the previous value. Code looks like this:

<c:set var="previousCustomer" value=""/>
<c:forEach items="${customerlist}" var="customer" varStatus="i">
   <c:choose>
      <c:when test="${(customer.account) != (previousCustomer)}">
         [do some stuff]
      </c:when>                         
      <c:otherwise>
         [do other stuff]
      </c:otherwise>
   </c:choose>
  <c:set var="previousCustomer" value="${customer.account}"/>
</c:forEach>

However, when I write out the value, previousCustomer always returns the same value as customerlist.account after it is set to customerlist.account. Is there any way to check the current value of an item in a loop vs. the previous value?

Was it helpful?

Solution

You can by using the varStatus attribute and EL brace notation:

<c:forEach items="${customerlist}" var="customer" varStatus="i">
  <c:choose>
    <c:when test="${not i.first and customerlist[i.index] eq customerlist[i.index - 1]}">
      [do some stuff]
    </c:when>                         
    <c:otherwise>
      [do other stuff]
    </c:otherwise>
  </c:choose>
</c:forEach>

So, check if you are not doing the fist iteration (since there is no previous object), using the varStatus first property:

not i.first

And then compare based on the varStatus index property

customerlist[i.index] eq customerlist[i.index - 1]

Alternatively you could use begin="1" in c:forEach to skip the first item in the list if you are sure there are more items in the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top