JSF中每条记录有多行?

问题描述:

有一个myfaces数据表,有可能有2 为每个记录? 我简单的一个行的表如下所示:JSF中每条记录有多行?

<h:dataTable id="somelist" value="#{MyBean.somelist}" var="item"> 
    <h:column> 
     <f:facet name="header"> 
      <h:outputText value="ID"/> 
     </f:facet> 
     <h:outputText value="#{item.id}"/> 
    </h:column> 
</h:dataTable> 

是的,在这种情况下。您可以通过自定义DataModel控制绑定到outputText的值。

public class TwoRowModel extends DataModel { 

    private List<Pair> values = initData(); 
    private int index = -1; 

    private List<Pair> initData() { 
     List<Pair> list = new ArrayList<Pair>(); 
     for (int i = 0; i < 5; i++) { 
      Pair pair = new Pair(); 
      pair.key = "Key " + i; 
      pair.value = "Value " + i; 
      list.add(pair); 
     } 
     return list; 
    } 

    @Override 
    public int getRowCount() { 
     return values.size() * 2; 
    } 

    @Override 
    public Object getRowData() { 
     Pair pair = values.get(index/2); 
     if (index % 2 == 0) { 
      return pair.key; 
     } else { 
      return pair.value; 
     } 
    } 

    @Override 
    public int getRowIndex() { 
     return index; 
    } 

    @Override 
    public Object getWrappedData() { 
     throw new UnsupportedOperationException("Demo code"); 
    } 

    @Override 
    public boolean isRowAvailable() { 
     int realIndex = index/2; 
     if (realIndex < 0) { 
      return false; 
     } 
     if (realIndex >= values.size()) { 
      return false; 
     } 
     return true; 
    } 

    @Override 
    public void setRowIndex(int idx) { 
     this.index = idx; 
    } 

    @Override 
    public void setWrappedData(Object value) { 
     throw new UnsupportedOperationException("Demo code"); 
    } 

    class Pair { 
     public String key; 
     public String value; 
    } 

} 

在这个演示代码,返回的值就是要显示的一个:

<h:dataTable id="somelist" value="#{twoRowModel}" var="item"> 
     <h:column> 
      <f:facet name="header"> 
       <h:outputText value="ID" /> 
      </f:facet> 
      <h:outputText value="#{item}" /> 
     </h:column> 
    </h:dataTable> 
+0

这看起来不错,我会尝试了这一点。 – 2008-12-10 15:57:32