Spring应用之I18N

Resource文件

  1. Register MessageSource

     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" >
          <property name="basename" value="message" />  <!-- messages是配置文件的前缀 -->
     </bean >
    
  2. 定义国际化需要的资源文件(置于classpath下),例如:

    • message.properties文件 (默认)
        language.cn=English
        menu.title=Menu
        ctrl.req.fail=Operate[{0}] request[ {1}] fail
      
    • message_zh_CN.properties文件
        language.en=英文
        menu.title=菜单
        ctrl.req.fail=操作{0}需求 {1}失败
      

PS 因为ApplicationContext也是MessageSource接口的实现,故可以直接调用getMessage()方法

Locale解析器

LocaleResolver(本地化解析器),会自动解析用户的本地化信息(即Locale),实现类:

  • AcceptHeaderLocaleResolver :检查请求中客户端浏览器发送的accept-language头信息,包含客户端操作系统的本地化信息
  • CookieLocaleResolver :检查客户端中的cookie是否包含本地化信息 ,若有就使用
  • SessionLocaleResolver :检查客户端中的session是否包含本地化信息,若有就使用
  • FixedLocaleResolver :返回一个固定的本地化信息,默认值为当前JVM的locale

例如:

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

Local拦截器

Local拦截器(可使用已有的,也可自定义处理)

例如:LocaleChangeInterceptor(拦截URL,获取Local参数值并进行本地化设置)

LocaleChangeInterceptor源码:

public class LocaleChangeInterceptor extends HandlerInterceptorAdapter {
    public static final String DEFAULT_PARAM_NAME = "locale";
    private String paramName = DEFAULT_PARAM_NAME;
    public void setParamName(String paramName) {
        this.paramName = paramName;
    }
    public String getParamName() {
        return this.paramName;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException {
        String newLocale = request.getParameter(this.paramName);
        if (newLocale != null) {
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            if (localeResolver == null) {
                throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
            }
            localeResolver.setLocale(request, response, StringUtils.parseLocaleString(newLocale));
        }
        // Proceed in any case.
        return true;
    }
}

配置使用:

<bean id ="localeChangeInterceptor" class= "org.springframework.web.servlet.i18n.LocaleChangeInterceptor" >
    <property name ="paramName" value= "language" /> <!-- 对URL中paramName为language的进行处理(默认paramName为local) -->
</bean >

<!-- 加入Local拦截器 -->
<mvc:interceptors>
    <bean ref="localeChangeInterceptor"> <!-- 拦截所有的URL请求 -->
    <!--
    <mvc:interceptor>
      <mvc:mapping path="/**" />
      <mvc:exclude-mapping path="/resources/**"/>
      <bean ref="localeChangeInterceptor"/>
    </mvc:interceptor> -->
</mvc:interceptors>

前端静态文字国际化

使用<spring:message>

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

<li>
     <a href ="?language=en">< spring:message code ="language.en" text ="English" /></a>
</li>
<li>
     <a href ="?language=zh_CN">< spring:message code ="language.cn" text= "Chinese" /></a>
</li>

MenuText : <spring:message code="menu.title" text="default text" />
CurrentLocale : ${pageContext.response.locale}

后端动态信息国际化

RequestContext requestContext = new RequestContext(request);
Locale myLocale = requestContext.getLocale();
System.out.println("-------------------------------------");
System.out.println(myLocale);
System.out.println(requestContext.getMessage("menu.title"));
System.out.println(requestContext.getMessage("ctrl.auth.fail",new Object[]{"Add","R028394"},"Operate Fail"));