史上最佳springboot Locale 国际化方案
1、国际化资源
使用IDEA创建资源组
2、编写配置
application.yml
增加国际化目录配置
增加配置类 从请求头获取多语言关键字
/** * 国际化配置 * * @author Lion Li */ @Configuration public class I18nConfig { @Bean public LocaleResolver localeResolver() { return new I18nLocaleResolver(); } /** * 获取请求头国际化信息 */ static class I18nLocaleResolver implements LocaleResolver { @NotNull @Override public Locale resolveLocale(HttpServletRequest httpServletRequest) { String language = httpServletRequest.getHeader("content-language"); Locale locale = Locale.getDefault(); if (StrUtil.isNotBlank(language)) { String[] split = language.split("_"); locale = new Locale(split[0], split[1]); } return locale; } @Override public void setLocale(@NotNull HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } } }
3、用法详解
在 Header 请求头 增加上下文语言参数 content-language
参数需与国际化配置文件后缀对应
如 zh_CN en_US 等
4、测试
编写测试类
/** * 测试国际化 * * @author Lion Li */ @RestController @RequestMapping("/demo/i18n") public class TestI18nController { @Autowired private MessageSource messageSource; /** * 通过code获取国际化内容 * code为 messages.properties 中的 key * * 测试使用 user.register.success */ @GetMapping() public String get(String code) { return messageSource.getMessage(code, new Object[]{}, LocaleContextHolder.getLocale()); } }
测试接口
到此这篇关于springboot Locale 国际化方案的文章就介绍到这了,更多相关springboot 国际化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Spring Cloud微服务架构Sentinel数据双向同步
这篇文章主要为大家介绍了Spring Cloud微服务架构Sentinel数据双向同步示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-10-10详解基于java的Socket聊天程序——服务端(附demo)
这篇文章主要介绍了详解基于java的Socket聊天程序——服务端(附demo),具有一定的参考价值,感兴趣的小伙伴们可以参考一下。2016-12-12SpringBoot整合mybatis使用Druid做连接池的方式
这篇文章主要介绍了SpringBoot整合mybatis使用Druid做连接池的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-08-08举例讲解Java的Jackson库中ObjectMapper类的使用
这篇文章主要介绍了举例讲解Java的Jackson库中ObjectMapper类的使用,Jackson库通常被用来实现Java的对象和JSON之间的转换功能,需要的朋友可以参考下2016-01-01
最新评论