【问题标题】:Access nested properties in variable EL expression访问变量 EL 表达式中的嵌套属性
【发布时间】:2013-04-15 05:14:17
【问题描述】:

通常,我可以访问嵌套 bean 的属性,在这种情况下,address_nameaddress 像这样:

#{customer.address.address_name}

假设我有一个字符串:

String addressPath = address.address_name

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

我试过了

#{customer[addressPath]}

但它只适用于直接属性。

【问题讨论】:

标签: java jsf jsf-2 seam el


【解决方案1】:

我不知道是否存在执行此操作的标准方法...但我使用在“costumer”bean(或范围内的辅助 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 框架或组件的库(seam、primefaces、richfaces、omnifaces 等)有一种方法来做这样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2019-12-30
    • 2013-03-13
    相关资源
    最近更新 更多