Spring中ApplicationContex的国际化出现中文乱码

在学习ApplicationContext对国际化支持的时候,发生中文乱码

错误点:message_zh_CN.properties的文件编码不是以 ASCII  编码存储的。

(该properties文件用记事本打开时,以 ASCII 编码的中文是类似:\u6B22\u8FCE\u4F60  ,如果记事本显示的是正常中文,则出错了)

 

解决方案:

1)File>Settings>Editor>File Encodings,勾选上 :Transparent native-to-ascii conversion .

2)然后右键你的 .properties文件 ,选择:Mark as Properties,这时你的properties会变成如下。

3)打开.properties文件,将原本的中文删除 ,重新写入

 

 


 

以下是我的国际化demo

1)beans.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
            驱动Spring调用messageSource Bean的setBasenames()方法
            setBasenames():需要一个数组参数,使用list元素配置多个数组元素
    -->
    <bean id="messageSource"     
         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        
        <property name="basenames">
            <list>
                <value>i18n/message</value>
                <!--如果有多个资源文件,列在此处-->
            </list>
        </property>

    </bean>
</beans>

2)message_zh_CN.properties

hello=\u6B22\u8FCE\u4F60,{0}
now=\u73B0\u5728\u65F6\u95F4\u662F\uFF1A{0}

3)message_en_US.properties

hello=welcome,{0}
now=now is :{0}

4)I18nTest.class

package test.java;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;
import java.util.Locale;

/**
 * @Author:蜡笔小新
 * @Date:2020/4/13 20:42
 */
public class I18nTest {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        String hello = ctx.getMessage("hello",new String[]{"蜡笔小新"}, Locale.getDefault(Locale.Category.FORMAT));
        String now = ctx.getMessage("now",new String[]{String.valueOf(new Date())}, Locale.getDefault(Locale.Category.FORMAT));

        System.out.println(hello);
        System.out.println(now);
    }
}

 

效果截图:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值