SpringBoot 国际化LocaleContextHolder的基本配置
在resources创建文件messages_zh_CN.properties(中文),写入#Unicode转码hello=\u4f60\u597Dmessages_en_US.properties(英文),写入hello=hello world结构如图创建配置类@Configuration@EnableAutoConfiguration@ComponentScanpublic class Loc
·
-
在resources创建文件
messages_zh_CN.properties(中文),写入
#Unicode转码 hello=\u4f60\u597D
messages_en_US.properties(英文),写入
hello=hello world
结构如图
-
创建配置类
@Configuration @EnableAutoConfiguration @ComponentScan public class LocaleConfig implements WebMvcConfigurer { //Cookie @Bean public LocaleResolver localeResolver() { CookieLocaleResolver localeResolver = new CookieLocaleResolver(); localeResolver.setCookieName("localeCookie"); //设置默认区域 localeResolver.setDefaultLocale(Locale.ENGLISH); //设置cookie有效期. localeResolver.setCookieMaxAge(3600); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); // 参数名 lci.setParamName("lang"); return lci; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
-
测试
@RestController public class TestController { @Autowired private MessageSource messageSource; @GetMapping(path = "/test2",produces = "text/html;charset=utf-8") public Object test2(){ Locale locale = LocaleContextHolder.getLocale(); String hello = messageSource.getMessage("hello", null, locale); return hello; } }
访问
http://127.0.0.1:8080/test2?lang=zh_CN
http://127.0.0.1:8080/test2?lang=en_US
更多推荐
已为社区贡献4条内容
所有评论(0)