2014-03-12 34 views
0

我有一个简单的bean在会话范围内提供“翻译方法”JSF/CDI:用绿豆请求字符串从资源

String getText(String key, Object args ...) { 

    ...// lookup in property resource 
    return value; 
} 

我想叫这个bean让我的UI组件本地化的文本字符串。当试图呼叫上述功能时,例如通过

 <p:outputLabel for="name" value="#{lang.getText(xyz,arg1)}" /> 
     <p:inputText id="name" value="#{formProject.entity.name}"/> 
     <p:message for="name" id="msgName" /> 

我得到java.lang.IllegalArgumentException异常:错误的参数数目

现在,我的问题

1) Is this generally a good alternative to <f:loadBundle> to localize my components? 
2) Since I am able to address my nested bean fields via bean1.bean2.myfield 
    how to avoid conflicts when adressing the properties dot-sepatated, 
    i.e. x.y.z instead of xyz? 

我不认为我是在右边跟踪当前...

回答

3

通常你应该使用

<?xml version='1.0' encoding='UTF-8'?> 
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"> 

    <application> 
     <locale-config> 
      <default-locale>it</default-locale> 
      <supported-locale>it</supported-locale> 
      <supported-locale>en</supported-locale> 
      <supported-locale>de</supported-locale> 
     </locale-config> 

     <resource-bundle> 
      <base-name>/bundle</base-name> 
      <var>bundle</var> 
     </resource-bundle> 
    </application> 

</faces-config> 

,并通过

<p:outputLabel for="name" value="#{bundle.foo}" /> 
<p:inputText id="name" value="#{formProject.entity.name}"/> 
<p:message for="name" id="msgName" /> 

获取标签,但同时,你可以访问点名称这样

<p:outputLabel for="name" value="#{bundle['foo.bar']}" /> 

你不能传递参数(我不知道如何在没有插补器的情况下做到这一点,或者如果可能的话)

的混合解决方案可以是

@ManagedBean 
public class LabelBean 
{ 
    private String getText(String key, String... args) 
    { 
     String message = Faces.evaluateExpressionGet("#{bundle['" + key + "']}"); 
     return MessageFormat.format(message, args); 
    } 

    public String getText1(String key, String arg) 
    { 
     return getText(key, arg); 
    } 

    public String getText2(String key, String arg1, String arg2) 
    { 
     return getText(key, arg1, arg2); 
    } 
} 

在类似的方式提出@hwellmann(1)

+0

感谢您的回答,很好的解决方法...... –

2

表达式语言不支持带可变参数的方法表达式。作为一种变通方法,您可以介绍的方法

String getText2(String key, Object arg1, Object arg2); 
String getText3(String key, Object arg1, Object arg2, Object arg3); 

关于2),只需使用#{lang.getText('x.y.z',arg1)}

+0

我认为如此。通过用户定义的标签调用多参数函数时会遇到同样的问题。 –