9

I have bean "MyBean", which has property HashMap - "map" which values type is MyClass. I want to show some properties of map in jsf using ui:repeat. But these code:

<ui:repeat  var="var"  value="#{mybean.map}" >
<tr> 
<td> <h:outputText value="#{var.value.property1}"></h:outputText> </td>
<td><h:outputText value="#{var.value.property2}"></h:outputText></td>
</tr>
</ui:repeat>

But this code didn't show anything. Though when I try to show hashmap values in jsp this way, it was succesfull. Where I am wrong? And how fix that?

Mat
  • 202,337
  • 40
  • 393
  • 406
Aram Gevorgyan
  • 2,175
  • 7
  • 37
  • 57
  • (@Aram: you need to put an empty line between normal text and code blocks, otherwise it doesn't format properly) – Mat May 14 '11 at 12:15

2 Answers2

26

That's indeed a major pita. The <c:forEach> supported Map for long. Apart from supplying another getter as suggested by McDowell, you could also workaround this by a custom EL function.

<ui:repeat value="#{util:toList(bean.map)}" var="entry">
    #{entry.key} = #{entry.value} <br/>
</ui:repeat>

where the EL function look like this

public static List<Map.Entry<?, ?>> toList(Map<?, ?> map) {
    return = map != null ? new ArrayList<Map.Entry<?,?>>(map.entrySet()) : null;
}

Or, if you're on EL 2.2 already (provided by Servlet 3.0 compatible containers such as Glassfish 3, Tomcat 7, etc), then just use Map#entrySet() and then Set#toArray().

<ui:repeat value="#{bean.map.entrySet().toArray()}" var="entry">
    #{entry.key} = #{entry.value} <br/>
</ui:repeat>
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Hi BalusC, your syntax `#{util:toList(bean.map)}`, is `util` a managed bean, BalusC? I never see this syntax before. – Thang Pham Apr 26 '12 at 01:28
  • @Thang: it's an EL function: http://stackoverflow.com/questions/7079978/how-to-create-a-custom-el-function/7080174#7080174 It's like as JSTL functions. [OmniFaces](http://wiki.omnifaces.googlecode.com/hg/vdldoc/index.html) has also some in `of` namespace, see `of:mapToList()`. – BalusC Apr 26 '12 at 02:45
6

From the documentation for the repeat value attribute:

The name of a collection of items that this tag iterates over. The collection may be a List, array, java.sql.ResultSet, or an individual java Object. If the collection is null, this tag does nothing.

So, var is set as your HashMap and EL tries to look up the key "value" on it. You will need to expose your entry set as a List.

McDowell
  • 107,573
  • 31
  • 204
  • 267
  • @Aram Gevorgyan - like `dataTable`, `repeat` is an index-based component (see the _offset_ and _size_ attributes). Adam Winer (who was in the JSF expert group) discusses a similar case here: [Using Sets with UIData](http://sfjsf.blogspot.com/2006/03/usings-sets-with-uidata.html). – McDowell May 14 '11 at 14:03