JSTL Sets and Lists - checking for the presence of an element in a set

I have a Java Set in my session and the variable is also in the session. I need to know if this variable exists in the set.

I want to use the contains (Object) method that Java has for lists and sets to check if this object exists in the set.

Can this be done in JSTL? If so, how? :)

Thanks, Alex

+29
list set jstl
Jul 02 '09 at 21:06
source share
2 answers

You can do this with JSTL tags, but the result is not optimal:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <body> <jsp:useBean id="numbers" class="java.util.HashSet" scope="request"> <% numbers.add("one"); numbers.add("two"); numbers.add("three"); %> </jsp:useBean> <c:forEach items="${numbers}" var="value"> <c:if test="${value == 'two'}"> <c:set var="found" value="true" scope="request" /> </c:if> </c:forEach> ${found} </body> </html> 



It is best to use a custom function:

 package my.package; public class Util { public static boolean contains(Collection<?> coll, Object o) { if (coll == null) return false; return coll.contains(o); } } 

This is defined in the TLD file ROOT / WEB-INF / tag / custom.tld:

 <?xml version="1.0" encoding="UTF-8"?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <short-name>myfn</short-name> <uri>http://samplefn</uri> <function> <name>contains</name> <function-class>my.package.Util</function-class> <function-signature>boolean contains(java.util.Collection, java.lang.Object)</function-signature> </function> </taglib> 

Then the function can be imported into your JSP:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="myfn" uri="http://samplefn"%> <html> <body> <jsp:useBean id="numbers" class="java.util.HashSet" scope="request"> <% numbers.add("one"); numbers.add("two"); numbers.add("three"); %> </jsp:useBean> ${myfn:contains(numbers, 'one')} ${myfn:contains(numbers, 'zero')} </body> </html> 



The next version of EL (due to JEE6) should allow a more direct form:

 ${numbers.contains('two')} 
+41
Jul 05 '09 at 14:22
source share

If you are using Spring Framework, you can use Spring TagLib and SpEL:

 <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> --- <spring:eval var="containsValue" expression="yourList.contains(yourValue)" /> Contains (true or false): ${containsValue} 
+1
Jul 20 '17 at 15:10
source share



All Articles