2013-02-25 33 views
1

我想通過編寫一個小的「樹」組件來獲得對JSF2內部組件的更好掌握,它需要一個節點結構並將其呈現爲簡單的ul/li元素。自定義組件:如何填充一個ELContext變量呈現兒童

應該可以定義道路,樹葉的內容呈現有點像這個(類似於H:數據表):

<custom:tree value="#{someBean.someListProperty}" var="nodeData"> 
    <h:outputText value="#{nodeData}" /> 
    ... 
</custom:tree> 

目前我正在努力搞清楚,如何「填充「該變量到當前上下文中。我想這樣的事情,但它沒有工作:

@Override 
@SuppressWarnings("unchecked") 
public void encodeChildren(FacesContext context) throws IOException { 
    if ((context == null)){ 
     throw new NullPointerException(); 
    } 

    ArrayList<String> list = (ArrayList<String>) getStateHelper().eval("value"); 
    String varname = (String) getStateHelper().eval("var"); 
    if(list != null){ 
     for(String str : list){ 
      getStateHelper().put(varname, str); 
      for(UIComponent child: getChildren()){ 
       child.encodeAll(context); 
      } 
     } 
    } 
} 

爲了簡化我第一次開始使用一個簡單的字符串ArrayList和迭代內容打印出來。這裏是xhtml:

<custom:tree value="#{testBean.strings}" var="testdata"> 
    <h:outputText value="#{testdata}" /> 
</custom:tree> 

那麼,實現這個的正確方法是什麼?

最好的問候, 基督教VOSS

+1

這是一個非常廣泛的主題,所以這裏只是給您一個開源的基於JSF樹組件鏈接,應提供一些見解:http://showcase.omnifaces.org/components/tree(你可以找到源代碼鏈接在底部) – BalusC 2013-02-25 19:59:39

回答

1

感謝BalusC,

保持它的簡單,這是基本的(或更好的一個可能的)回答我的問題:

你可以把一個新的將給定鍵下的變量放到requestMap中,任何子組件都可以使用指定的ValueExpression訪問它。

@Override 
@SuppressWarnings("unchecked") 
public void encodeChildren(FacesContext context) throws IOException { 
    if ((context == null)){ 
     throw new NullPointerException(); 
    } 

    ArrayList<String> list = (ArrayList<String>) getStateHelper().eval("value"); 
    String varname = (String) getStateHelper().eval("var"); 
    Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); 

    varStore = requestMap.get(varname); // in case this Object already exists in the requestMap, 
             // emulate "scoped behavior" by storing the value and 
             // restoring it after all rendering is done. 

    if(list != null){ 
     for(String str : list){ 
      requestMap.put(varname, str); 
      for(UIComponent child: getChildren()){ 
       child.encodeAll(context); 
      } 
     }   
     // restore the original value 
     if(varStore != null){ 
      requestMap.put(varname, varStore); 
     }else{ 
      requestMap.remove(varname); 
     } 
    } 
}