Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output a map collection in facelets JSF 2

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>
like image 878
Adam Avatar asked Nov 17 '11 04:11

Adam


2 Answers

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.

like image 100
BalusC Avatar answered Sep 21 '22 23:09

BalusC


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>
like image 27
Adam Avatar answered Sep 24 '22 23:09

Adam