Spring MVC在代码中获取国际化信息


本文基于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方法,如下所示:

  1. public class MenuServiceImpl implements MenuService, ServletContextAware {  
  2.         private ServletContext servletContext;  
  3.   
  4.     /* 
  5.      * (non-Javadoc) 
  6.      *  
  7.      * @see 
  8.      * org.springframework.web.context.ServletContextAware#setServletContext 
  9.      * (javax.servlet.ServletContext) 
  10.      */  
  11.     @Override  
  12.     public void setServletContext(ServletContext servletContext) {  
  13.         this.servletContext = servletContext;  
  14.     }  
  15.   
  16.     public void test() {  
  17.         WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  
  18.     }  
  19. }  

       如此,我们取得了WebApplicationContext信息。

        其次,如何获取当前使用的Locale信息?一行代码搞定:

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

相关内容