Spring Boot國際化開發實戰

本章將講解如何在Spring Boot和Thymeleaf中作頁面模板國際化的支持,根據系統語言環境或者session中的語言來自動讀取不一樣環境中的文字。spring

國際化自動配置

Spring Boot中已經對國際化這一塊作了自動配置。緩存

國際化自動配置類:微信

org.springframework.boot.autoconfigure.context.MessageSourceAutoConfigurationcookie

查看自動配置源碼有如下主要幾個參數:session

private String basename = "messages";

private Charset encoding = Charset.forName("UTF-8");

private int cacheSeconds = -1;

private boolean fallbackToSystemLocale = true;

basename:默認的掃描的國際化文件名爲messages,即在resources創建messages_xx.properties文件,能夠經過逗號指定多個,若是不指定包名默認從classpath下尋找。mvc

encoding:默認的編碼爲UTF-8。ide

cacheSeconds:加載國際化文件的緩存時間,單位爲秒,默認爲永久緩存。編碼

fallbackToSystemLocale:當找不到當前語言的資源文件時,若是爲true默認找當前系統的語言對應的資源文件如messages_zh_CN.properties,若是爲false即加載系統默認的如messages.properties文件。url

國際化實戰

一、國際化配置spa

spring:
    messages:
        fallbackToSystemLocale: false
        basename: i18n/common, i18n/login, i18n/index

二、在i18n目錄下建立如下幾個文件

如index.properties,index_zh_CN.properties,index.properties做爲找不到定義語言的資源文件時的默認配置文件。

建立對應的key/value,如:

index_zh_CN.properties

index.welcome=歡迎

index.properties

index.welcome=welcome

三、添加語言解析器,並設置默認語言爲US英文

LocaleResolver接口有許多實現,如能夠從session、cookie、Accept-Language header、或者一個固定的值來判斷當前的語言環境,下面是使用session來判斷。

@Bean
public LocaleResolver localeResolver() {
	SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
	sessionLocaleResolver.setDefaultLocale(Locale.US);
	return sessionLocaleResolver;
}

四、添加切換語言過濾器

private LocaleChangeInterceptor localeChangeInterceptor() {
	LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
	localeChangeInterceptor.setParamName("lang");
	return localeChangeInterceptor;
}

添加以上過濾器並註冊到spring mvc中

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

而後頁面經過訪問指定的url?lang=zh_CN進行切換。

五、經過#{}來讀取資源文件

如Thymeleaf模板文件中使用:

<label th:text="#{index.welcome}"></label>

默認會讀取英文的資源文件並顯示:welcome

推薦:Spring Boot & Cloud 最強技術教程

掃描關注咱們的微信公衆號,乾貨天天更新。

image

相關文章
相關標籤/搜索