Spring Boot國際化支持
國際化支持應該是所有的做國際化網站都需要考慮的一個問題,Spring Boot為國際化提供了強有力的支持,本文將會通過一個例子來講解Spring Boot的國際化。
添加Maven支持
Spring Boot本身就支持國際化,我們這裡添加一個模板支持來通過頁面來展示,我們這裡添加thymeleaf模板:
<code><dependency> <groupid>org.springframework.boot/<groupid> <artifactid>spring-boot-starter-thymeleaf/<artifactid>/<dependency>/<code>
LocaleResolver
我們需要為系統指定一個默認的LocaleResolver:
<code>@Beanpublic LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.US); return slr;}/<code>
上面的例子中我們自定義了一個SessionLocaleResolver,並且指定了默認的Locale。
LocaleChangeInterceptor
接下來,我們定義一個LocaleChangeInterceptor來接收Locale的變動。這裡我們通過lang參數來接收。
<code>@Beanpublic LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); lci.setParamName("lang"); return lci;}/<code>
當然,我們需要將這個Interceptor註冊到SpringMVC中:
<code>@Overridepublic void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor());}/<code>
定義Message Sources
默認情況下,Spring Boot會在src/main/resources查找message文件,默認的message文件是messages.properties,如果指定了某種語言,那麼就是messages_XX.properties,其中XX是Local code。
messages.properties是key value的格式,如果在對應的local文件中沒找到相應的key,則會在默認的messages.properties中查找。
我們默認定義英語的messages.properties如下:
<code>greeting=Hello! Welcome to our website!lang.change=Change the languagelang.eng=Englishlang.fr=French/<code>
同時我們定義一個法語的message文件messages_fr.properties :
<code>greeting=Bonjour! Bienvenue sur notre site!lang.change=Changez la languelang.eng=Anglaislang.fr=Francais/<code>
Controller文件
我們定義一個跳轉的controller文件:
<code>@Controllerpublic class PageController { @GetMapping("/international") public String getInternationalPage() { return "international"; }}/<code>
html文件
相應的html文件如下:
<code> <title>Home/<title>
:<select> <option> <option> <option>/<select>/<code>
運行應用程序
好了,接下來我們可以運行了。
如果我們訪問http://localhost:8080/international?lang=en , 則會讀取默認的英語資源:
通過切換到法語環境:http://localhost:8080/international?lang=fr, 我們可以看到:
環境已經切換過來了。
最後:
上面都是自己整理好的!我就把資料貢獻出來給有需要的人!順便求一波關注,哈哈~各位小夥伴關注我後私信【Java】就可以免費領取噠
閱讀更多 Java天天 的文章