本文基于Spring MVC 注解-让Spring跑起来。本文提到的国际化是Spring实现国际化的方案之一。
(1) 在applicationContext.xml中添加以下配置信息:
- <!-- 国际化配置 -->
- <bean id="messageSource"
- class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basename" value="messages.messages" />
- </bean>
- #message_en.properties
- main.title=RUI manage system
- #message_zh_CN.properties
- main.title=RUI管理系统
(2) 在dispatcher.xml中添加以下配置信息
- <!-- 国际化配置 -->
- <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
并添加拦截器配置:
- <mvc:interceptors>
- <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
- </mvc:interceptors>
(3) 在jsp页面中调用国际化后的信息
- <fmt:message key="main.title" />
(4) 访问系统,只需要在初次访问系统时,在地址拦上添加"?locale=en"即可访问英文网站。注意,访问系统的第一个页面时添加即可,后绪可不再添加。
本文基于Spring MVC国际化。
在Spring MVC国际化一文中描述了如何实现Spring的国际化,也描述了在jsp页面中如何获取国际化信息,本文描述如何在java代码中获取国际化信息。
在Java代码中,获取国际化信息使用org.springframework.web.context.WebApplicationContext的getMessage方法,getMessage方法中需要使用当前的Locale信息,于是,怎样获取国际化信息集中在以下两点:
1. 如何获取WebApplicationContext?
2. 如何获取当前使用的Locale?
首先,如何获取WebApplicationContext呢,很简单,在任何一个类实现org.springframework.web.context.ServletContextAware并重写其setServletContext方法,如下所示:
- public class MenuServiceImpl implements MenuService, ServletContextAware {
- private ServletContext servletContext;
- /*
- * (non-Javadoc)
- *
- * @see
- * org.springframework.web.context.ServletContextAware#setServletContext
- * (javax.servlet.ServletContext)
- */
- @Override
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
- public void test() {
- WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
- }
- }
如此,我们取得了WebApplicationContext信息。
其次,如何获取当前使用的Locale信息?一行代码搞定:
- Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
- String menuName = applicationContext.getMessage("text.menu.name",null, "菜单A", locale);