Spring國際化

一、什麼是Spring國際化

Spring國際化是一個方便地支持多種語言的應用程序的機制,它可以將一個應用程序翻譯成多個語言版本。在Spring中,使用ResourceBundleMessageSource實現的。此外,Spring支持基於請求頭、Session以及cookie的語言切換。

在Spring國際化中,需要準備兩個文件,分別是message文件和properties文件。

其中,message文件是一個XML文件,包含了一個bean,bean的類型是org.springframework.context.support.ResourceBundleMessageSource,該bean用於讀取properties文件中定義的消息。

而properties文件則是一個包含鍵值對的文件,每個鍵值對代表了一條信息。Spring默認會讀取classpath下名字為messages的properties文件。

二、如何在Spring中實現國際化

1.配置ResourceBundleMessageSource實現國際化支持



<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
    <list>
      <value>messages</value>
      <value>other</value>
    </list>
  </property>
</bean>

在上述配置中,我們配置了一個id為messageSource的bean,類型為ResourceBundleMessageSource,並通過basenames屬性指定了需要讀取的properties文件。基於這個配置,Spring容器會自動將messageSource注入到其他組件中,以便它們能通過messageSource讀取不同的語言消息。

例如,可以通過以下方式讀取消息:


@Autowired
private MessageSource messageSource;

public void someMethod() {
  String message = messageSource.getMessage("message.key", new Object[] {"John"}, Locale.US);
}

代碼中通過@Autowired注入了MessageSource組件,並通過getMessage方法讀取了指定鍵值的message。

使用getMessage方法,需要傳入三個參數,分別是message的key,替換Message中佔位符的參數以及locale語言。

2.基於請求頭實現語言切換

在Spring MVC中,可以通過LocaleResolver接口實現基本的國際化支持。在這種情況下,Spring MVC會嘗試通過解析請求頭來獲取客戶端的locale語言信息。

我們可以實現OwnLocaleResolver類,該類實現了LocaleResolver接口,並實現了setLocale和getLocale方法。在setLocale方法中,我們將locale信息存入cookie中。


public class OwnLocaleResolver implements LocaleResolver {
  private static final String COOKIE_NAME = "lang";
  private static final String LANG_EN = "en";
  private static final String LANG_ZH = "zh";

  @Override
  public Locale resolveLocale(HttpServletRequest request) {
    String lang = readCookie(request, COOKIE_NAME);
    if (!StringUtils.isEmpty(lang)) {
      if (LANG_EN.equals(lang)) {
        return Locale.ENGLISH;
      } else if (LANG_ZH.equals(lang)) {
        return Locale.CHINESE;
      }
    }
    return request.getLocale();
  }

  @Override
  public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    writeCookie(response, COOKIE_NAME, locale.getLanguage(), 30*3600*24*365);
  }

  private String readCookie(HttpServletRequest request, String cookieName) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
          return cookie.getValue();
        }
      }
    }
    return null;
  }

  private void writeCookie(HttpServletResponse response, String name, String value, int maxAge) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    cookie.setPath("/");
    response.addCookie(cookie);
  }
}

在自定義的LocaleResolver生效之前,需要在配置中添加以下配置:



  <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang"/>
  </bean>
</mvc:interceptors>

在添加自定義的LocaleResolver實現後,我們還需要啟用Spring的國際化功能。最後需要在Spring MVC的ViewResolver中增加一個LocaleResolver,代碼如下:


<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <beans:property name="prefix" value="/WEB-INF/pages/"/>
    <beans:property name="suffix" value=".jsp"/>
    <beans:property name="localeResolver" ref="localeResolver"/>
</beans:bean>

3.基於Session實現語言切換

通過使用基於Session的LocaleResolver實現語言切換,我們可以通過透明地在用戶的session中存儲locale信息,來靈活地控制用戶的語言環境。 為了使用SessionLocaleResolver,我們需要在Spring的Bean配置中添加如下內容:


<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />

啟用Spring的國際化功能後,我們需要將SessionLocaleResolver注入到Controller中,並通過setLocale方法來設置語言信息。例如,可以通過以下方式實現:


@RequestMapping("testLanguage")
public String testLanguage(HttpServletRequest request, HttpServletResponse response, 
  HttpSession session) {
  Locale locale = new Locale("en", "US");
  session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
  return "redirect:index";
}

三、 小結

通過配置ResourceBundleMessageSource、基於請求頭和基於Session實現語言切換,我們可以通過簡單的代碼來支持多語言環境。Spring MVC支持相當複雜的國際化場景,比如用戶語言環境可在頁面中自由切換、不同類型的消息可在多個地方進行多語言支持等。

原創文章,作者:NRRCI,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/368942.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
NRRCI的頭像NRRCI
上一篇 2025-04-12 13:00
下一篇 2025-04-12 13:00

相關推薦

發表回復

登錄後才能評論