# Internationalization ###### tags: `Spring` `Internationalization` ## /pom.xml 需要注入[thymeleaf](https://www.thymeleaf.org/)套件 ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` ## /src/main/java/{package}/WebMvcConfigurer 加入 @Bean 與 [攔截器](https://www.tutorialspoint.com/spring_boot/spring_boot_interceptor.htm) ``` @Configuration public class WebMvcConfigurer extends WebMvcConfigurerAdapter { /** * 攔截器 * @return */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } /** * 預設本地語言 * @return */ @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.TAIWAN); return slr; } /** * 修改語言 * @return */ @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); lci.setParamName("lang");//根據取得GET[lang]的值,來決定顯示哪種語言 return lci; } } ``` ## 新增語言包 1. 中文語言包(messages.properties)(預設檔名) ``` greeting=你好 lang.change=選擇語言 lang.en=英文 lang.ch=中文 ``` 2. 英文語言包(messages_en.properties) ``` greeting=Hello! Welcome to our website! lang.change=Change the language lang.en=English lang.ch=Chinese ``` ## .XSL 需加入 xmlns:th="http://www.thymeleaf.org",以便使用 thymeleaf 的標籤 ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:th="http://www.thymeleaf.org"> <xsl:output encoding="UTF-8" media-type="text/html" method="html" indent="no" omit-xml-declaration="yes" /> <xsl:template match="/"> <HTML lang="zh-TW" > <HEAD> <TITLE>首頁</TITLE> <SCRIPT src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></SCRIPT> <SCRIPT src="/page.js"></SCRIPT> </HEAD> <BODY> <xsl:apply-templates select="document"/> </BODY> </HTML> </xsl:template> <xsl:template match="document"> <H1 th:text="#{greeting}"></H1> <SPAN th:text="#{lang.change}"></SPAN> <SELECT id="locales"> <OPTION value=""></OPTION> <OPTION value="ch" th:text="#{lang.ch}"></OPTION> <OPTION value="en" th:text="#{lang.en}"></OPTION> </SELECT> </xsl:template> </xsl:stylesheet> ``` ## DEMO 根據GET[lang]的值決定要預設的語言包   [前往 Spring Security](https://hackmd.io/@LeeLo/HJvoNobgL) [前往 Spring Security Acl](https://hackmd.io/@LeeLo/HJD8s_NUH) [前往 Spring Boot Redis](https://hackmd.io/@LeeLo/HJBTC6Xb8) [前往 Spring Security防止暴力破解身份驗證](https://hackmd.io/@LeeLo/HJyI3yEWL)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up