21.8.5 地区更改拦截器LocaleChangeInterceptor

You can enable changing of locales by adding the LocaleChangeInterceptor to
one of the handler mappings (see [Section 21.4, “Handler mappings”]($publish-21-8-mvc.html

mvc-handlermapping “21.4 Handler mappings” )). It will detect a parameter in

the request and change the locale. It calls setLocale() on the
LocaleResolver that also exists in the context. The following example shows
that calls to all *.view resources containing a parameter named
siteLanguage will now change the locale. So, for example, a request for the
following URL, <http://www.sf.net/home.view?siteLanguage=nl> will change the
site language to Dutch.

你可以在处理器映射(详见21.4 处理器映射(Handler mappings)小节)前添加一个LocaleChangeInterceptor拦截器来更改地区信息。它能检测请求中的参数,并根据其值相应地更新地区信息。它通过调用LocaleResolversetLocale()方法来更改地区。下面的代码配置展示了如何为所有请求*.view路径并且携带了siteLanguage参数的资源请求更改地区。举个例子,一个URL为<http://www.sf.net/home.view?siteLanguage=nl>的请求将会将站点语言更改为荷兰语。

  1. <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  2. <property name="paramName" value="siteLanguage"/>
  3. </bean>
  4. <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>
  5. <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  6. <property name="interceptors">
  7. <list>
  8. <ref bean="localeChangeInterceptor"/>
  9. </list>
  10. </property>
  11. <property name="mappings">
  12. <value>/**/*.view=someController</value>
  13. </property>
  14. </bean>