spring的i18n国际化消息翻译使用demo

需求

有些项目需要交付给国内/国外使用,这个时候就需要切换系统语言环境了。

思路

spring有集成的i18n,当然是拿来直接用了。
用spring的拦截器获取请求中的参数,比如下面这种lang=en_US(en:代表语言,US代表城市),当然参数也可以放在请求头里,这个看具体灵活实现了。

localhost:9007/i18n/user?key=username&lang=en_US

如果不知道语言和城市枚举的,可以从下面这个类中寻找

java.util.Locale

配置

配置yml

Spring Boot中国际化文件的名称默认为messages,messages.properties表示默认的,里面可以没有值,但必须有这样的一个文件.如果采用Spring Boot默认的查找路径,那么直接放在resources顶级目录下即可。但如果想放到其他目录下,比如statistics/i18n/目录下,则需要在application.properties中配置如下:

pring.messages.basename=statistics/i18n/messages

前面是没有斜杠的,表示相对路径。而文件名为messages,也不需要添加properties后缀。用过Spring Boot的都知道它会为咱们处理的。

需要配置messages.properties默认文件原因
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration.ResourceBundleCondition#getResources
在这里插入图片描述

yml配置

spring:    
  messages:
    basename: i18n/message		#翻译文件父路径,message是文件名前缀
    encoding: UTF-8				#编码
    cache-duration: 3600		#缓存存活时间

在这里插入图片描述

在这里插入图片描述

为什么要设置一个空的message.properties呢->可以查看源码得知
在这里插入图片描述
在这里插入图片描述

配置默认语言

package com.felix.spring_cloud_one.i18n.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

@Configuration
public class LocaleConfig {



    /**
     * 默认解析器 其中locale表示默认语言
     */
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.CHINA);
        return localeResolver;
    }

}

配置拦截器

package com.felix.spring_cloud_one.i18n.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 采用默认的LocaleChangeInterceptor作为拦截器来指定切换国际化语言的参数名。
     * 比如当请求的url中包含?lang=zh_CN表示读取国际化文件messages_zh_CN.properties。
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);
    }
}

参考了多篇博文
https://www.cnblogs.com/mzq123/p/11925325.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值