spring boot+thymeleaf 设置多国语言

首先要在src根目录下新建三个文档,位置很关键,试了好多次才试出来的

文件名:messages.properties (默认)
内容为:head.button.semi=中转仓

文件名:messages_en_US.properties (英文)
内容为:head.button.semi=Semi

文件名:messages_zh_CN.properties (中文)
内容为:head.button.semi=中转仓

需要改变语言的地方用 th:text="#{head.button.semi}" 代替
比如

另外要添加切换链接,用于切换


接着在src/main目录下
新建一个拦截MultiLanguageConfig.java

package main;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
@Configuration
public class MultiLanguageConfig implements WebMvcConfigurer {	
	@Bean
	public LocaleResolver localeResolver() {
		SessionLocaleResolver slr = new SessionLocaleResolver();
		slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
		return slr;
	}
	@Bean
	public LocaleChangeInterceptor localeChangeInterceptor() {
		LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
		lci.setParamName("lang");
		return lci;
	}
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(localeChangeInterceptor());
	}
}

搞定

另外推荐复杂版

你可能感兴趣的:(spring,boot)