JSTL Sets and Lists - checking if item exists in a Set

Alex Genadinik picture Alex Genadinik · Jul 2, 2009 · Viewed 49.6k times · Source

I have a Java Set in my session and a variable also in the session. I need to be able to tell if that variable exists in the set.

I want to use the contains ( Object ) method that Java has for Lists and Sets to test whether that object exists in the set.

Is that possible to do in JSTL? If so, how? :)

Thanks, Alex

Answer

McDowell picture McDowell · Jul 5, 2009

You could do this using 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>

A better way would be 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 a 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>

The function can then be imported into your JSPs:

<%@ 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 in JEE6) should allow the more direct form:

${numbers.contains('two')}