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,所以建議一定要準備這份保底檔案。
在 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,後續頁面不必再帶參數。
Spring 內建三種 LocaleResolver,依需求挑一種即可:
若同一個 Spring 容器裡宣告了多個 LocaleResolver,必須用 defaultLocaleResolver 屬性明確指出要用哪一個,否則啟動就會失敗。