Try   HackMD

Internationalization

tags: Spring Internationalization

/pom.xml

需要注入thymeleaf套件

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

/src/main/java/{package}/WebMvcConfigurer

加入 @Bean 與 攔截器

@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=中文
  1. 英文語言包(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]的值決定要預設的語言包

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

前往 Spring Security
前往 Spring Security Acl
前往 Spring Boot Redis
前往 Spring Security防止暴力破解身份驗證