【问题标题】:How to call method with optional parameter list in JSF2 / EL 2.2如何在 JSF2 / EL 2.2 中使用可选参数列表调用方法
【发布时间】:2012-04-11 02:34:09
【问题描述】:

知道如何(如果可能的话)从 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.

【问题讨论】:

    标签: java jsf-2 el optional-parameters optional-arguments


    【解决方案1】:

    EL 不支持可变参数。

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

    例如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.propertiestext_de.properties 等,符合ResourceBundle API 规则。

    另见:

    【讨论】:

    • ehm...这只是示例(-:我不喜欢 x+y=z 之类的示例,所以我将其塑造为国际化示例...我的错误。但我不得不说 h :outputFormat 听起来不错,我刚刚学到了一些新东西。
    • 由于不支持可变参数(由您确认),我只有三个方法,带有一/二/三个参数来处理调用等可变参数。不好但工作)-:
    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2013-03-11
    相关资源
    最近更新 更多