Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

set

jstl

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')}

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}