Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring MVC 國際化三步驟:配置、攔截器與頁面取值

Spring 的國際化機制可以完全靠配置完成,不必在程式碼裡到處寫 if-else 判斷語言。以下是以注解方式建置的 Spring MVC 專案為例,整理最精簡的三個步驟。

步驟一:定義訊息來源

在 applicationContext.xml 中加入:

<!-- 國際化配置 -->
<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages.messages" />
</bean>

messages.messages 的寫法需要拆開看:前一個 messages 是 src 下的資料夾名稱,後一個 messages 代表「所有以 messages 開頭、.properties 結尾的檔案」。也就是說,實際檔案是:

# message_en.properties
main.title = RUI manage system
# message_zh_CN.properties
main.title = RUI管理系統

檔名的 _en、_zh_CN 對應 Java 的 Locale 寫法,Spring 會依當前 Locale 自動挑選;若都找不到對應檔,則退回無後綴的 messages.properties,所以建議一定要準備這份保底檔案。

步驟二:註冊 LocaleResolver 與攔截器

在 dispatcher.xml 中加入:

<!-- 國際化配置 -->
<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />

並加上攔截器,讓使用者得以切換語言:

<mvc:interceptors>
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>

這兩個 bean 是一組的:SessionLocaleResolver 把使用者選的語言存進 Session,LocaleChangeInterceptor 則負責攔下帶有 locale 參數的請求並寫入其中。少了攔截器,網址上的參數就不會生效。

步驟三:在頁面中取值

<fmt:message key="main.title" />

記得在 JSP 頂端引入標籤庫:

<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>

驗證

第一次造訪系統時,在網址後方加上 ?locale=en 就會看到英文介面。因為用的是 SessionLocaleResolver,語言選擇會存進 Session,後續頁面不必再帶參數。

Resolver 的選擇

Spring 內建三種 LocaleResolver,依需求挑一種即可:

  • AcceptHeaderLocaleResolver:直接採瀏覽器設定的語言,不做切換,也是預設值。
  • SessionLocaleResolver:語言存 Session,適合讓使用者主動切換(本文用法)。
  • CookieLocaleResolver:語言存 Cookie,關掉瀏覽器前都記得,跨裝置體驗較一致。

若同一個 Spring 容器裡宣告了多個 LocaleResolver,必須用 defaultLocaleResolver 屬性明確指出要用哪一個,否則啟動就會失敗。

Copyright © Linux教程網 All Rights Reserved