您的位置:首页 > 编程语言 > Java开发

springmvc 国际化

2016-07-15 00:00 417 查看
摘要: 最近有用到springmvc的国际化,贴出来记录一下

1。配置文件springmvc.xml

<!-- 国际化支持 -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n/test_i18n" />
</bean>

<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en_US" />
</bean>

<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>

<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>

红字标示的为存放i18文件的文件夹,且在src目录下

2。配置controller,根据用户自己的选择,修改语言环境

if(lang.equals("zh")){
Locale locale = new Locale("zh", "CN");
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
}else if(lang.equals("en")){
Locale locale = new Locale("en", "US");
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
}else
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());

}

3。配置完成就可以用了,通常会有以下几种情况

2.1 页面信息的国际化,比如加载一个注册表单,那么 用户名/username 应该根据语言环境呈现。

jsp 页面引入s 标签

<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

需要国际化的地方,引入对应的i18 属性

<spring:message code="loginpage.username"/>

2.2 第二种情况是提示信息,比如用户提交表单,邮箱格式不合法,可以用过下面的方法获取国际化信息

locale = (Locale) httpRequest.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);

或者:

Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

String message = applicationContext.getMessage(code,args, locale);

getMessage中有四个变量,依次分别为message_*.properties文件中的key,key中{0}、{1}等对应的值,默认值和Locale。

再将拿到的信息返回页面

2.3 还有其他的情形,比如jquery 的提示信息等等,官方好像有提供方案,待研究
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: