Output a map collection in facelets JSF 2
Asked Answered
A

2

12

I have seen a couple other examples on SO discussing some weird workarounds but none seem to work and they were all addressed at versions prior to JSF 2. So, it it possible to simply output the keys of a map? I've tried ui:repeat and c:forEach like below with no luck:

<c:forEach items="${myBean.myMap.keySet}" var="var">
   <h:outputText value="#{var}"/>
</c:forEach>
Alanis answered 17/11, 2011 at 4:37 Comment(1)
I figured it out. I'll post in 8 hours when SO lets me.Alanis
A
17

From your code:

<c:forEach items="${myBean.myMap.keySet}" var="var">

This is not going to work. This requires a getKeySet() method on the Map interface, but there is none.

If your environment supports EL 2.2 (Servlet 3.0 containers like Tomcat 7, Glassfish 3, etc), then you should invoke the keySet() method directly instead of calling it as a property:

<c:forEach items="#{myBean.myMap.keySet()}" var="key">
    <h:outputText value="#{key}"/>
</c:forEach>

Or if your environment doesn't support EL 2.2 yet, then you should iterate over the map itself directly which gives a Map.Entry instance on every iteration which in turn has a getKey() method, so this should do as well:

<c:forEach items="#{myBean.myMap}" var="entry">
    <h:outputText value="#{entry.key}"/>
</c:forEach>

None of above works with <ui:repeat> as it doesn't support Map nor Set. It supports List and array only. The difference between <c:forEach> and <ui:repeat> is by the way that the <c:forEach> generates multiple JSF components during view build time and that the <ui:repeat> creates a single JSF component which generates its HTML output multiple times during view render time.

Aspirant answered 17/11, 2011 at 11:23 Comment(1)
I like your answer better. More detail. I remember you! You're an answer junkie. You rock man!Alanis
A
10

It turns out the correct syntax to output map keys is:

<ui:repeat value="#{myBean.myMap().keySet().toArray()}" var="var">
   <h:outputText value="#{var}"/><br/>
</ui:repeat>
Alanis answered 17/11, 2011 at 22:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.