5

Need help.I have a hash map which is returned from a spring controller to JSP.Is there a way just to check if a certain key exists irrespective of any value(the value may be null too)

Say, the below hash map is being sent from the controller

HashMap hmap = new HashMap();
hmap.put("COUNTRY", "X");
hmap.put("REGION", null);

If the key REGION exists ( value may be anything including null) then display some section in the jsp.

I am trying to access the key as ${hmap['REGION']}

Thanks in advance.

Amar
  • 955
  • 3
  • 11
  • 28

3 Answers3

11

try using containsKey:

${hmap.containsKey('REGION')}
Vipul Paralikar
  • 1,508
  • 10
  • 22
  • 2
    @Amz - In order 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. – Vipul Paralikar Aug 07 '14 at 11:19
  • if you don't have a new version of tomcat you can use the fn:containsKey(map,key) from the functions taglib – EdgeCaseBerg Oct 24 '14 at 17:41
  • 1
    @EdgeCaseBerg Eh? fn:containsKey? Never heard of this JSTL function! https://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/fn/tld-summary.html – Geeb Oct 20 '15 at 10:55
4
<c:forEach var="entry" items="${hmap }" varStatus="status">        
      <c:if test="${entry.key == 'REGION'}">
        <tr>
           <td>${entry.key}</td>
           <td>${entry.value}</td>
        </tr>
      </c:if>
</c:forEach>

Check this, if this solution works or not ? And post if not working and also post your JSP's jstl code.

user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62
3

I know that you want to test for where the value may include null, but there's a solution by using the empty operator that is elegant when one might want to also exclude null values in that it will evaluate to true if the value is null or does not exist.

<c:if test="${not empty hmap['REGION']}">
    <%-- conditional block --%>
</c:if>
Brett Ryan
  • 26,937
  • 30
  • 128
  • 163