How to call a method with an optional parameter list in JSF2 / EL 2.2

any idea how (if at all possible) to call a java method with optional parameters from a JSF page? Iam using Java 7, JSF 2.1, EL 2.2 (Glassfish 3.1.2). Thanks in advance...

I got this exception

javax.el.ELException: /example.xhtml: wrong number of arguments
Caused by: java.lang.IllegalArgumentException: wrong number of arguments

      

Sample page

<h:outputText value="#{bean.methodWithParameters('key.en.currentDate', '2012-01-01', '00:00')}"/>
<h:outputText value="#{bean.methodWithParameters('key.en.currentTime', '12:00')}"/>

      

Bean example

public String methodWithParameters(String key, Object ... params) {
    String langValue = LanguageBean.translate(key);
    return String.format(langValue, params);
}

      

Property example

key.en.currentDate=Today is %s and current time is %s.
key.en.currentTime=Current time is %s.

key.en.currentDate=Today is %1$s and current time is %2$s.
key.en.currentTime=Current time is %2$s.

      

+3


source to share


1 answer


Varargs is not supported in EL.

As far as your specific functional requirement is concerned, you are approaching it completely wrong. You shouldn't reinvent internationalization / localization in JSF, but instead use the facilities provided by JSF. To do this, you must use <resource-bundle>

in faces-config.xml

or <f:loadBundle>

in your Facelets. This will upload files using the ResourceBundle

API and use the MessageFormat

API to format messages. Then you can format the strings <h:outputFormat>

with <f:param>

.

eg. com/example/i18n/text.properties

key.en.currentDate=Today is {0} and current time is {1}.
key.en.currentTime=Current time is {0}.

      

View:



<f:loadBundle baseName="com.example.i18n.text" var="text" />

<h:outputFormat value="#{text['key.en.currentDate']}">
    <f:param value="2012-01-01" />
    <f:param value="00:00" />
</h:outputFormat>

      

Further, I'm not sure if this one en

in the key means English or not, but if it really means language, then you are making another mistake. Individual languages ​​should each have their own properties

file, for example text_en.properties

, text_de.properties

etc. ResourceBundle

API rules.

See also:

+5


source







All Articles