Reputation: 13407
I am using Java 8, Tomcat 8, with Servlet 3.1.0, JSP 2.0 and JSTL 1.2.
I expected to be able to do the following. However, it does not work.
<c:forEach var="item" items="${itemList}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${item.itemCode}</td>
<td>${item.displayName}</td>
<td>
<c:choose>
<c:when test="${user.favourites.contains(item)}">Yes</c:when>
<c:otherwise>No</c:otherwise>
</c:choose>
</td>
</tr>
</c:forEach>
where user.favourites
is a Set
of item
s
Could it be that I do not have the right versions of the dependencies. My POM contains;
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
servlet-api
and jsp-api
are provided by Tomcat. Is the version for jstl
correct?
Upvotes: 4
Views: 18298
Reputation: 13407
It turns out that it does work, but that I had another issue at hand.
My entities (item
and user
) are coming from Hibernate, from two different DAOs in two different queries, and so the item
in the favourites
list was a different object to the item
in the itemList
.
I had not implemented (overridden) the hashCode()
and equals()
methods in my User
and Item
classes, and so the Collection.contains()
was just looking at object identity not equivalence.
As soon as I implemented hashCode()
and equals()
methods, it all worked as expected.
The way I found this out was I decided to implement a custom TLD function that invoked the Collection.contains(...)
method, and then noticed that even that was returning false
.
Upvotes: 4
Reputation: 889
You can use the contains function provided in JSTL tag library. Kindly find more details @ JSTL fn:contains() Function
This would help you.
Upvotes: -3