2015-11-10 47 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

谢谢你的回答。不幸的是,我无法将新属性添加到现有组件。有相当多的页面使用这个组件,我不应该改变。 –