3

知道如何(如果可能的话)从 JSF 页面调用带有可选参数的 java 方法吗?我正在使用 Java 7、JSF 2.1、EL 2.2(Glassfish 3.1.2)。提前致谢...

我得到了这个例外

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

页面示例

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

豆示例

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

属性示例

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.
4

1 回答 1

5

EL 不支持可变参数。

至于您的具体功能要求,您完全错误地处理了这个问题。您不应在 JSF 中重新发明国际化/本地化,而应使用 JSF 提供的工具。为此,您应该在 Facelets 文件<resource-bundle>faces-config.xml或在其中使用。<f:loadBundle>这将通过ResourceBundleAPI 加载文件并使用MessageFormatAPI 来格式化消息。然后,您可以<h:outputFormat>使用 with格式化字符串<f:param>

例如com/example/i18n/text.properties

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

看法:

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

此外,我不确定en键中的那个是否代表英语,但如果它确实代表语言,那么你又犯了一个错误。不同的语言需要有自己的properties文件,如text_en.properties,text_de.properties等符合ResourceBundleAPI 规则。

也可以看看:

于 2012-03-27T14:39:54.280 回答