java.util.Map.contains() method call in JSP

10,791

Solution 1

${fooBean.fooMap.containsValue("baz")}

The above will work in JSP 2.2 or better. If you're using a pre-JSP 2.2 container (e.g. Java EE 5) then an EL function is probably the better solution.

Static Java method:

package contains;
import java.util.Map;
public class Maps {
    public static boolean containsValue(Map<?, ?> map, Object value) {
        return map.containsValue(value);
    }
}

The file WEB-INF/tlds/maps.tld:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1"
  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">
  <tlib-version>1.0</tlib-version>
  <short-name>maps</short-name>
  <uri>/WEB-INF/tlds/maps</uri>
   <function>
    <description>Returns true if the value is contained</description>
    <name>containsValue</name>
    <function-class>contains.Maps</function-class>
    <function-signature>
      boolean containsValue(java.util.Map, java.lang.Object)
    </function-signature>
  </function>
</taglib>

Usage:

<%@taglib prefix="maps" uri="/WEB-INF/tlds/maps" %>
...
${maps:containsValue(fooBean.fooMap, "baz")}

Solution 2

I'll assume that you're talking about using EL in JSP the right way and thus not the old fashioned scriptlets, otherwise the answer is extremely obvious like as given by AlexR.

You can use the empty keyword to test for the presence of a non-null and non-empty value associated with a key.

<c:if test="${not empty bean.map['somekey']}">
    Map contains a non-null/non-empty value on key "somekey".
</c:if>

If you really need to invoke the map's containsKey() or containsValue() methods, then you need to ensure that you're running a Servlet 3.0 compatible container like Tomcat 7, Glassfish 3, JBoss AS 6, etc and that your web.xml is declared conform Servlet 3.0. This way you can utilize a new EL 2.2 feature: invoking non-getter methods with arguments.

<c:if test="${bean.map.containsKey('somekey')}">
    Map contains key "somekey".
</c:if>
<c:if test="${bean.map.containsValue('somevalue')}">
    Map contains value "somevalue".
</c:if>

Solution 3

You can use scriptlet code:

<%= yourBean.getMapProperty().contains() %>

It's not pretty, but it should work. There may also be some tag libraries available that do something similar.

Share:
10,791
user325643
Author by

user325643

Updated on June 04, 2022

Comments

  • user325643
    user325643 almost 2 years

    Is there a way to call java.util.Map.contains() method in JSP where the Map is a property of a bean.