作為<f:loadBundle>的替代方案,我一直在開發一個新的<s:messageSource>組件,該組件可用于公開來自任何Spring MessageSource的消息,并提供其他一些優點。
新組件是<f:loadBundle>的直接替代。
<s:messageSource source="#{messageSource}" var="messages"/>
<p><h:outputText value="#{messages.hello}"/>
</p>
source屬性可以是任何解析為MessageSource實例的EL表達式。 如果未指定源,則將使用Spring ApplicationContext 。 var屬性是將用于訪問消息的變量的名稱。
如果您在XHTML中引用了忘記定義的消息,則將看到警告消息(在開發中),或者將引發異常(在生產中)。
與標準JSF一樣,您的消息并包含與<h:outputFormat>一起使用的占位符
pages.message.simple.welcome=Welcome to {1} with {0}
<h:outputFormat value="#{messages.welcome}"><f:param value="Spring"/><f:param value="JSF"/>
</h:outputFormat>
<h:outputFormat>標簽有點冗長,因此為了方便起見,Spring消息可以用作Map 。 這使您可以更簡潔地引用占位符:
<h:outputText value="#{messages.welcome['Spring']['JSF']}"/>
相同的語法允許您將Java對象映射到消息。 默認情況下,對象是通過從類名稱構建消息鍵來映射的。 例如,以下類:
package org.example;
public class ExampleObject {
}
可以在JSF中引用:
<h:outputText value="#{messages[exampleInstance]}"/>
解決以下消息:
org.example.ExampleObject=example
對于枚舉對象,消息鍵包括枚舉名稱和類:
package org.example;
public enum ExampleObject {ONE, //mapped to message key org.example.ExampleObject.ONETWO //mapped to message key org.example.ExampleObject.TWO
}
對象消息還可以引用應構成消息一部分的屬性:
org.example.PersonName=Name is {first} {last}
...package org.example;
public class PersonName {...public String getFirst() {...}public String getLast() {...}
}
您還可以通過使用實現org.springframework.springfaces.message.ObjectMessageSource接口的消息源來定義自己的對象消息策略。
如果要檢查其中的任何代碼,請查看GitHub Project中的org.springframework.springfaces.message和org.springframework.springfaces.message.ui軟件包。
參考: Phil Webb博客博客中來自我們JCG合作伙伴 Phillip Webb的Spring和JavaServer Faces集成:國際化和本地化 。
翻譯自: https://www.javacodegeeks.com/2012/06/spring-jsf-integration.html