本文基于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);WebApplicationContext信息和Locale信息都获取到后,再用一行代码获取国际化信息:
String menuName = applicationContext.getMessage("text.menu.name",null, "菜单A", locale);在getMessage中有四个变量,依次分别为message_*.properties文件中的key,key中{0}、{1}等对应的值,默认值和Locale。