Question

I have a simple bean offering a 'translation method' in session scope

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

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

I am trying to call this bean to get my UI components localized text strings. When trying to call the above mentioned function, e.g. by

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

I get a java.lang.IllegalArgumentException: wrong number of arguments

Now, my question

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?

I don't think i am on the right track currently...

Was it helpful?

Solution

generally you should use

<?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>

and get labels via

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

but while you can access dotted names this way

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

you can't pass arguments (i don't know how to do it without an interpolator, or if it is possible at all)

an hybrid solution can be

@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);
    }
}

in similar way @hwellmann proposed (+1)

OTHER TIPS

Expression Language does not support method expressions with varargs. As a workaround, you could introduce methods

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

etc.

Regarding 2), simply use #{lang.getText('x.y.z',arg1)}.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top