I need to display Map
using <h:dataTable>
. My backing bean has a Map
property as below:
public class Bean {
private Map<Integer,String> map; // +getter
@PostConstruct
public void init() {
map = new TreeMap<Integer,String>();
map.put(1,"Sasi");
map.put(2,"Pushparaju");
map.put(3,"Venkat Raman");
map.put(3,"Prabhakaran");
}
}
Then in JSF page I am trying to bind this Map
property to the value
attribute of <h:dataTable>
.
<h:dataTable border="1" value="#{bean.map}" var="map">
<h:column id="column1">
<f:facet name="header">
<h:outputText value="UserId"></h:outputText>
</f:facet>
<h:outputText value="#{map.getKey}"></h:outputText>
</h:column>
<h:column id="column2">
<f:facet name="header">
<h:outputText value="Email Id"></h:outputText>
</f:facet>
<h:outputText value="#{map.getValue}"></h:outputText>
</h:column>
</h:dataTable>
It is giving en error that getKey
and getValue
is not present. I can understand that this is not the correct way to do it. How can I present a Map
using <h:dataTable>
?
Regarding to the last answer from prageeth, you may use entrySet instead of keySet; then you can get rid of myBean.map.get. See this example:
This works on myfaces 2.2.3 as I've just used it myself.
Annotation: I'd better had commented the last post, but my reputation is not high enough, therefore this is an extra answer.
You can try this alternative too.
Until upcoming JSF 2.3,
UIData
components such as<h:dataTable>
,<p:dataTable>
, etc and<ui:repeat>
does not support iterating over aMap
. This is only supported in<c:forEach>
.One way is to convert the map entries to an array (alone
entrySet()
won't work asUIData
also doesn't supportSet
until upcoming JSF 2.3).Another way is to wrap the map's entry set in a collection which the
<h:dataTable>
can iterate over, such as anArrayList
.However, more clean, self documenting and reusable is to use a
List<User>
instead wherein theUser
class has the necessary propertiesid
andname
.