2015-11-10 50 views
0

獲取bean類我有複合材料部件:從複合材料部件

<my:component value="#{bean.property1.property2}/> 

從複合材料部件,我需要得到類bean.property1讀取其註解。 我做到這一點通過下面的代碼:

ValueExpression valueExpression = expressionFactory.createValueExpression(FacesContext.getCurrentInstance().getELContext(), 
         "#{bean.property1}", Object.class); 
Object bean = valueExpression.getValue(FacesContext.getCurrentInstance().getELContext()); 
Class<?> beanClass = bean.getClass(); 

這種運作良好,但如果我通過ui:param使用my:component從facelet裏,並通過bean作爲參數,這並不工作,因爲bean不能得到解決。

也許我應該使用FaceletContext作爲ELContext而不是FacesContext.getCurrentInstance().getELContext()

FaceletContext faceletElContext = (FaceletContext) FacesContext.getCurrentInstance().getAttributes() 
        .get("javax.faces.FACELET_CONTEXT"); 

但這並不對RENDER_RESPONSE階段工作(從encodeBegin法)。它返回最後使用的ELContext而不是實際的上下文(我並不感到驚訝:))。

目標是從my:component獲得#{bean.property1}的等級。我該怎麼做?

回答

0

這很容易與RichFaces

ValueExpressionAnalayser analyser = new ValueExpressionAnalayserImpl(); 
    ValueDescriptor valueDescriptor = analyser.getPropertyDescriptor(context, valueExpression); 
    Class<?> beanClass = valueDescriptor.getBeanType(); 

這是確定我。

還有ValueExpressionAnalayzer in javax.faces.validator包,但它是封裝私有的,不能使用。

+0

JSF自己的'ValueExpressionAnalayzer'是一個包私有類,因此不幸公開可用。爲此,OmniFaces還有一個'org.omnifaces.el.E​​xpressionInspector'。它甚至支持從EL表達式中提取方法參數(在a.o.''中使用)。 – BalusC

+0

@BalusC你是對包私人。我編輯了我的答案。我應該看看OmniFaces。它與RichFaces相處嗎? –

+0

幾個OmniFaces工件已經用RF 4.5進行測試。至少,它應該像PrimeFaces一樣並排運行。 OmniFaces滿足於與任何JSF組件庫兼容。如果您發現與最新RF版本有任何兼容性問題,請通過任何方式報告[問題](https://github.com/omnifaces/omnifaces/issues)。 – BalusC

0

您可以將bean作爲參數傳遞給組件。

1)中聲明組件接口文件中的屬性(如果使用的是複合部件):

<cc:interface componentType="myComponentClass"> 
    <cc:attribute name="myBean" preferred="true"/> 
    ..others attributes 
<cc:interface> 

2)實施爲在 「爲myBean」 屬性的各吸氣和setter組件類(myComponentClass)

protected enum PropertyKeys { 
    myBean; 

    String toString; 

    PropertyKeys(String toString) { 
     this.toString = toString; 
    } 

    PropertyKeys() {} 

    @Override 
    public String toString() { 
     return ((this.toString != null) ? this.toString : super.toString()); 
    } 
} 
public YourBeanClass getMyBean() { 
    return (YourBeanClass) getStateHelper().eval(PropertyKeys.myBean, null); 
} 
public void setMyBean(YourBeanClass myBean) { 
    getStateHelper().put(PropertyKeys.myBean, myBean); 
} 

3)設置你的屬性JSF頁面:

<my:component myBean="#{bean}"/> 

4)在組件的render類中將UIComponent強制轉換爲myComponentClass。

@Override 
public void encodeBegin(FacesContext pContext, UIComponent pComponent) 
    throws IOException { 
    myComponentClass myComponent = (myComponentClass) pComponent; 
    myComponent.getYourAttribute(); 
} 
+0

謝謝你的回答。不幸的是,我無法將新屬性添加到現有組件。有相當多的頁面使用這個組件,我不應該改變。 –