1:添加配置类
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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
@Configuration
public class I18nConfig extends WebMvcConfigurerAdapter {
@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());
}
}
2:添加资源文件
默认读取路径在resources下:
可在application.properties中添加属性设置 :
#i18n configuation
spring.messages.basename=i18n/messages
效果如下图:
messages.properties是默认访问资源
3:网页切换语言
于url上拼接属性 如下
?lang=en_US
该属性会存于cookie中,网页跳转将继续使用该语言:
Cookie:JSESSIONID=9EFE46F94D0F89A9E7FBD1073631DEC5; hudson_auto_refresh=false; ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE=d3A3NzE5MTAwMTI6MTQ4MjczNzMxNjkxMjpkZDQ2MzM2NTc3ZmM3ZjU1Y2UzYjk2YWU2NjkwNjlmMjNmMjQwMDhhZmRlOGQxOWQ0YzRjOTM4ZTAwNzYwZmM5; jenkins-timestamper-offset=-28800000; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=en_US
最后一行即为存于cookie中的 语言属性
4:controller层中语言属性
LocaleContextHolder.getLocale()
可获取Locale类
可用如下代码进行语言判断:
LocaleContextHolder.getLocale().equals(Locale.US)
如有意见 请于评论指出 谢谢~