繁体   English   中英

访问变量EL表达式中的嵌套属性

[英]Access nested properties in variable EL expression

通常,我可以访问嵌套bean的属性,在这种情况下, address address_name如下所示:

#{customer.address.address_name}

假设我有一个String:

String addressPath = address.address_name

如何使用#{customer}#{addressPath}访问address_name

我试过了

#{customer[addressPath]}

但这仅适用于直接财产。

我不知道是否存在执行此操作的标准方法...但是我使用在“ costumer” bean(或作用域中的helper bean)中创建方法来以编程方式评估动态形成的EL表达式。

您可以实现这样的方法:

    public class Costumer{
        ...
            public Object eval(String exp) {
               //Concatenate your bean name or do it before method call instead
               //to get a String with a content like: "customer.address.address_name"
               exp = "customer." + exp;

               FacesContext facesContext = getFacesContext();
               Application appContext = facesContext.getApplication();
               ExpressionFactory expFactory = appContext.getExpressionFactory();
               ELContext expContext = facesContext.getELContext();
               ValueExpression valExp = expFactory.createValueExpression(expContext,exp, Object.class);

               return valExp.getValue(expContext);
             }
       ...
    }

然后,您只需要使用以下方式调用此方法:

#{customer.eval(addressPath)}#{customer.eval(myScopedBean.addressPath)}

我认为,存在更好的解决方案,也许您的JSF框架或组件的库(缝,素面,richfaces,omnifaces等)具有执行此操作的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM