基于session进行国际话,其它的配置就不写了,仅仅写,国际化要添加的配置。这个是在 spring-mvc.xml 添加
<!-- 国际话的相关配置 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!--①通过基名指定资源,相对于类根路径-->
<property name="basenames">
<list>
<value>classpath:i18n/danfosi</value>
</list>
</property>
<!--刷新资源文件的周期,以秒为单位 -1 代表永不刷新 为了测试方便 -->
<property name="cacheSeconds" value="-1"/>
</bean>
<!-- 存储区域设置信息 -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<!-- 基于Session的国际化实现 -->
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="locale" />
</bean>
</mvc:interceptors>
基于session国际话,会把 设置的语言保存进session,好处就是 在一个地方进行设置就可以了。
比如: 我仅仅是 在 登录界面 或者首页 进行设置
// 设置 语言的接口,当然 也可以写入 其它接口。
@RequestMapping("/setSession")
public void session(
@RequestParam(value="locale", defaultValue="en_US") String langType,
HttpServletRequest request, HttpServletResponse response) {
Locale locale = null;
if(StringUtils.isBlank(langType)){
locale = new Locale("en", "US");
}else{
String[] temp = langType.split("\\_");
locale = new Locale(temp[0], temp[1]);
}
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
//顺便写一个获取 资源文件中 的值,不如我取的就是 key为test的值 test=hello
// RequestContext req = new RequestContext(request);
// String msg = req.getMessage("test");
}
页面内容
$("#zhong").on("click",function(){
$.ajax({
url:"../danfoss/i18n/setSession?locale=zh_CN",
type:"GET"
});
})
$("#ying").on("click",function(){
$.ajax({
url:"../danfoss/i18n/setSession?locale=en_US",
type:"GET"
});
})
<button id="zhong">中文</button> <button id="ying">英文</button>