开发者

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

开发者 https://www.devze.com 2023-03-13 05:10 出处:网络
Is there开发者_JAVA技巧 a way to call java.util.Map.contains()method in JSP where the Map is a property of a bean.${fooBean.fooMap.containsValue(\"baz\")}

Is there开发者_JAVA技巧 a way to call java.util.Map.contains() method in JSP where the Map is a property of a bean.


${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")}


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>


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.


Since JSP is just a java you can call what you want. Just try it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号