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

时间:2013-04-22 10:26:32

标签: java jsf jsf-2 seam el

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

#{customer.address.address_name}

让我们说,我有一个字符串:

String addressPath = address.address_name

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

我试过

#{customer[addressPath]}

但它只适用于直接属性。

1 个答案:

答案 0 :(得分:0)

我不知道是否存在标准的方法来执行此操作...但我使用创建一个方法进入“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等)有一种方法可以做这样的事情。

相关问题