【发布时间】:2011-07-17 10:42:21
【问题描述】:
我用属性文件(例如:messages_en_US.properties、messages_de_DE.properties)制作了一个支持 i18n 的 Spring(2.5.6) Web 应用程序。
这个 .properties 文件带有 uni-codes。例如:
busy = Besch\u00E4ftigt
当从messageSource 读取busy 关键字时,会得出以下结果:
...
private static ReloadableResourceBundleMessageSource messageSource;
/**
* Gets a message from the resources (.properties) defined in the applicationContext.xml
*
* @param input string to hook up
* @return the the message hooked up from the resources
*/
public static String getMessage(String input){
System.out.println(input); //busy
System.out.println(messageSource.getDefaultEncoding()); //UTF-8
System.out.println(messageSource.getMessage(input, null, null)); //Beschu00E4ftigt
return messageSource.getMessage(input, null, null);
}
...
所以没有\
服务器上的文件也是UTF-8:
问题发生的环境:
- Tomcat 5.5.28(从
common/lib运行jsp-api.jar和servlet-api.jar) - JDK 1.5.0_22
JSTL 1.1.2(从应用程序
lib读取)Tomcat 6.0.32(从
lib运行jsp-api.jar和servlet-api.jar)- JDK 1.5.0_22
- JSTL 1.1.2(从应用程序
lib读取)
解决问题的环境(完全相同的分布):
- Tomcat 6.0.32(从 lib 运行 jsp-api.jar 和 servlet-api.jar)
- JDK 1.6.0_13
- JSTL 1.1.2(从应用程序lib读取)
如果您需要更多信息,请告诉我。不要说我需要更新我的 JDK,因为这是不可能的。
更新 applicationContext.xml 中的绑定 messageSource
<b:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<b:property name="defaultEncoding" value="UTF-8"/>
<b:property name="fallbackToSystemLocale" value="false" />
<b:property name="basenames">
<b:list>
<b:value>classpath:messages</b:value>
<b:value>/public/custom/i18n/portalmessages</b:value>
</b:list>
</b:property>
<b:property name="cacheSeconds" value="1"/>
</b:bean>
更新 2:将资源属性文件放在类路径上并使用类加载器:
URLClassLoader cl = (URLClassLoader) IOUtils.class.getClassLoader();
InputStream resourceAsStream = cl.getResourceAsStream("messages_de_DE.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
System.out.println("From classpath --> " + prop.get("busy")); //Beschäftigt
System.out.println("From i18n folder --> " + I18nFunctions.getMessage("busy")); //Beschu00E4ftigt
【问题讨论】:
-
您能否发布一段来自
applicationContext.xml的摘录,它定义了ReloadableResourceBundleMessageSource messageSource? -
@Harry Lime:查看帖子更新
-
看来
ReloadableResourceBundleMessageSource中的规则this.propertiesPersister.load(props, new InputStreamReader(is, encoding));在编码为“UTF-8”时遇到问题。当我将编码改回ISO-8859-1时,问题就解决了。现在我只需要签入例如中文代币作品。 -
不幸的是,这种改进并非在所有情况下都有效,因此我制作了一个未定义编码的 CustomResourceBundleMessageSource 并使用
props.load(inputstream)
标签: java unicode utf-8 internationalization character-encoding