关于SpringMVC 的国际化操作

来源:互联网 发布:常用数据库管理系统 编辑:程序博客网 时间:2024/06/05 01:09
一、首先就是要有国际化资源文件如:
i18n_en_US.properties
i18n_zh_CN.properties
i18n.properties
有以上命名的国际化资源文件。
其中有中英文两种形式。
i18n_zh_CN.properties 的内容为:
i18n.user=用户名
i18n.password=密码
i18n_en_US.properties 和 i18n.properties 的内容为:
i18n.user=User
i18n.password=PassWord

二、在 SpringMVC.xml(SpringMVC的配置文件) 中添加

1、ResourceBundleMessageSource :用于配置国际化资源,同时配置自定义的数据校验错误信息也会用到。
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource" >
<property name="basename" value="i18n"></property>
</bean>

2、配置 SessionLocaleResolver,此处用来进行页面转换中英文,进行国际化
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">、
</bean>

3、配置 LocaleChangeInterceptor 拦截器(配置拦截器需要用到 <mvc:interceptors> )
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>

三、使用国际化
1、在 jsp 文件中
利用 jstl 的 fmt 标签(key 对应着 国际化资源文件中的名称)
<fmt:message key="i18n.user"></fmt:message>
<br><br>
<fmt:message key="i18n.password"></fmt:message>
<br><br>
<a href="i18n?locale=zh_CN">中文</a>
<br>
<a href="i18n?locale=en_US">English</a>


2、导入 private ResourceBundleMessageSource messageSource; 可以对其进行相关操作

@RequestMapping("/i18n")
//locale为需要转换的本地语言
public String testI18n(Locale locale){
String val = messageSource.getMessage("i18n.user", null, locale);
System.out.println(val);
return "i18n";
}
0 0
原创粉丝点击