springboot实现国际化

发布于:2024-03-11 ⋅ 阅读:(67) ⋅ 点赞:(0)
  • 引言

今天在开发过程中,遇到国外客户,要求项目一些返回msg中,不能再有中文,于是便有了国际化需求。

  • How to do
        1.在项目resources下创建i18n文件夹以及messages.properties文件

                messages.properties 国际化主文件

phoneErr.msg=The phone number err

                messages_en.properties 英文配置文件

phoneErr.msg=The phone number err

                messages_zh.properties 中文配置文件

phoneErr.msg=手机号错误

                这三个文件缺一不可

        2.在项目中创建MyLocaleResolver.java

@Configuration
public class MyLocaleResolver {

    @Bean
    public LocaleResolver localeResolver() {
        log.info("LocaleResolver loading...");
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); // 设置默认语言
//        slr.setDefaultLocale(Locale.US); // 设置默认语言
        return slr;
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

}

        3.切换中英文,采用自定义spring拦截器方式

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor());
    }

    class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            String header = request.getHeader("Accept-Language");
            if (StrUtil.isBlank(header)) {
                return true;
            } else if ("zh".equals(header)) {
                LocaleContextHolder.setLocale(Locale.SIMPLIFIED_CHINESE);
            } else if ("en".equals(header)) {
                LocaleContextHolder.setLocale(Locale.US);
            }
            return true;
        }
    }
}

                前端可在接口请求头中添加 Accept-Language=en/zh 用于区别中英

        4.应用

    @Autowired
    private MessageSource messageSource;
    
    @RequestMapping("/test")
    public String getMessage() {
//        根据code从环境中自动获取对应国际化内容
        return messageSource.getMessage("phoneErr.msg", null, LocaleContextHolder.getLocale());
    }

        5.测试

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到