何时以及如何在faces-config.xml中使用<resource-bundle>和<message-bundle>标签进行本地化?这两者之间的区别对我来说不是很清楚。
发布于 2010-04-19 23:21:27
只要您想要覆盖JSF默认的警告/错误消息,就需要使用<message-bundle>,这些消息是由JSF验证/转换工具使用的。您可以在JSF specification的2.5.2.4章中找到默认警告/错误消息的关键字。
例如,com.example.i18n包中的Messages_xx_XX.properties文件会覆盖默认的required="true"消息,如下所示:
com/example/i18n/Messages_en.properties
javax.faces.component.UIInput.REQUIRED = {0}: This field is requiredcom/example/i18n/Messages_nl.properties
javax.faces.component.UIInput.REQUIRED = {0}: Dit veld is vereist可以按如下方式进行配置(不带区域设置说明符_xx_XX和文件扩展名!):
<message-bundle>com.example.i18n.Messages</message-bundle>只要您想注册一个本地化的资源束,就可以在整个<resource-bundle>应用程序中使用它,而无需在每个视图中指定<f:loadBundle>。
例如,com.example.i18n包中的Text_xx_XX.properties文件如下:
com/example/i18n/Text_en.properties
main.title = Title of main page
main.head1 = Top heading of main page
main.form1.input1.label = Label of input1 of form1 of main pagecom/example/i18n/Text_nl.properties
main.title = Titel van hoofd pagina
main.head1 = Bovenste kop van hoofd pagina
main.form1.input1.label = Label van input1 van form1 van hoofd pagina可以按如下方式进行配置(不带区域设置说明符_xx_XX和文件扩展名!):
<resource-bundle>
<base-name>com.example.i18n.Text</base-name>
<var>text</var>
</resource-bundle>在main.xhtml中的用法如下:
<h:head>
<title>#{text['main.title']}</title>
</h:head>
<h:body>
<h1 id="head1">#{text['main.head1']}</h1>
<h:form id="form1">
<h:outputLabel for="input1" value="#{text['main.form1.input1.label']}" />
<h:inputText id="input1" label="#{text['main.form1.input1.label']}" />
</h:form>
</h:body>ValidationMessages (JSR303 Bean验证)
自JavaEE6/JSF2以来,还有新的JSR303 Bean验证API,它由javax.validation.constraints包的@NotNull、Size、@Max等批注表示。您应该明白,此API是与JSF完全无关的。它不是JSF的一部分,但是JSF恰好在验证阶段支持它。即,它确定并识别JSR303实现(例如,Hibernate Validator)的存在,然后将验证委托给它(顺便说一下,可以使用<f:validateBean disabled="true"/>禁用验证)。
根据JSR303 specification的第4.3.1.1章,自定义JSR303验证消息文件需要让准确地命名为 ValidationMessages_xx_XX.properties,并且需要将其放置在类路径的根中(因此,不是放在包中!)。
本地化
在上述示例中,文件名中的_xx_XX表示(可选)语言和国家/地区代码。如果这完全不存在,那么它将成为默认(回退)包。如果该语言存在,例如_en,则当客户端在Accept-Language HTTP请求报头中显式请求该语言时,将使用该语言。这同样适用于国家/地区,例如_en_US或_en_GB。
您可以在faces-config.xml的<locale-config>元素中为消息和资源包指定受支持的语言环境。
<locale-config>
<default-locale>en</default-locale>
<supported-locale>nl</supported-locale>
<supported-locale>de</supported-locale>
<supported-locale>es</supported-locale>
<supported-locale>fr</supported-locale>
</locale-config>需要通过<f:view locale>设置所需的区域设置。另请参见Localization in JSF, how to remember selected locale per session instead of per request/view。
https://stackoverflow.com/questions/2668161
复制相似问题