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

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

+3
source share
4 answers
${fooBean.fooMap.containsValue("baz")}

The above will work in JSP 2.2 or higher. If you are using a pre-JSP 2.2 container (e.g. Java EE 5), then the EL function is probably the best solution.

Java static method:

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

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>

Using:

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

I assume that you are talking about using EL in JSP in the right direction and therefore not in old-fashioned scripts, otherwise the answer is very obvious, as AlexR did.

empty , .

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

containsKey() containsValue() , , Servlet 3.0 , Tomcat 7, Glassfish 3, JBoss AS 6 .., web.xml Servlet 3.0. , EL 2.2: .

<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>
+8

You can use the script code:

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

This is not very, but it should work. There may also be some tag libraries that do something similar.

+2
source

Since JSP is just Java, you can name whatever you want. Just give it a try.

0
source

All Articles