使用Spring MVC 配置国际化,用户可以选择语言,前台后台获取国际化资源的方法:
config :
spring-mvc.xml
<!-- 国际化 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 国际化信息所在的文件名 -->
<property name="basename" value="messages" />
<!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 -->
<property name="useCodeAsDefaultMessage" value="true" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" >
<property name="defaultLocale" value="en" />
</bean>
jsp:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:message code="key" />
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:message key="key" />
后台方式:
在方法里面:
RequestContext context = new RequestContext(request);
String message = context.getMessage("key");
或者使用
//使用 LocaleContextHolder.getLocale() 获取当前语言
//使用类 继承 ApplicationContextAware 接口,获取到 ApplicationContext 对象
//获取国际化资源文件对象
Map<String, MessageSource> map =ApplicationContext.getBeansOfType(MessageSource.class)
//可以获取对应的
String value = MessageSource.getMessage(code, args, LocaleContextHolder.getLocale());
用户修改 语言(以下两种均可):
1.配置controller,
在对应的方法里面:
首先 构造一个 Locale 对象,使用 Locale里面的属性,或者 new Locale(String language, String country),
然后使用:
RequestContext context = new RequestContext(request);
context.changeLocale(Locale locale);
//或者
LocaleContextHolder.setLocale(Locale locale);
2.配置
<bean id="changeLocale" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="interceptors">
<list>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
</list>
</property>
</bean>
然后 访问controller 的路径为:
<a href="/sys/test?locale=zh_CN">中文</a>