版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38001814/article/details/87394100
在项目中,一般有请求访问时先根据请求所带的内容获取到其语言,然后设置到线程中,在用到国际化的地方时通过Spring的MessageSource类根据线程中的语言自动展现
设置语言及获取语言思路:通过ThreadLocal实现,在每一个访问的请求线程内均设置语言,在该线程的生命周期内当使用到国际化语言时可以立马获取该语言变量,隔离了其他线程。
简易代码实现:
public class I18nContext {
private static ThreadLocal<Map<String, String>> threadLocal = ThreadLocal.withInitial(HashMap::new);
public static void setLang(String language) {
Map<String, String> map = new HashMap<>();
map.put("i18n.test", language);
threadLocal.set(map);
}
public static String getLang() {
return threadLocal.get().get("i18n.test");
}
}
MessageSource实现过程:
1、首先在spring配置文件中引入MessageSource
<!-- 国际化 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>test</value>
</list>
</property>
</bean>
2、在resource目录下新增国际化配置文件,文件名称一般以xxx_en_US.properties形式建立,这里测试只建立了中英文配置文件
ps:如果是第一次往properties文件中写中文,可能会导致待会测试时读取该中文值乱码的情况,那是因为写的时候是以utf-8编码写入,idea就算配置了在运行时自动转为ascii可能也会失效,所以第一次输入时请务必将中文转为ascii
那么如何在idea中将中文转为ascii呢?
首先进入terminal终端,然后请看下图命令,输入native2ascii之后按下回车,然后输入你需要转换的中文再按回车即转换完毕
如何把properties文件中的ascii自动转为中文?请移步:idea解决properties文件中文乱码的问题
3、测试代码:
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
MessageSource messageSource = (MessageSource) context.getBean("messageSource");
String info1 = messageSource.getMessage("hello",null, Locale.getDefault());
String info2 = messageSource.getMessage("hello",null, Locale.US);
System.out.println("zh_CN info1 :" + info1);
System.out.println("en_US info2 :" + info2);
输出:
以上即能完成Spring项目中国际化语言的基本需求了