侧边栏壁纸
博主头像
王小木人

这是很长,很好的一生

  • 累计撰写 141 篇文章
  • 累计创建 43 个标签
  • 累计收到 9 条评论

目 录CONTENT

文章目录

springboot整合i18n 实现国际化语言切换 通过在请求头中传递参数切换语言

王小木人
2022-04-04 / 0 评论 / 0 点赞 / 3,523 阅读 / 3,526 字

springboot 默认自动集成了i18n来实现多种语言切换,网上大多数的国际化语言切换都是通过在接口上增加一个lang的参数来实现,但是这样做使得接口变得臃肿不易维护,但是在发起请求 我们通过像token那样加在请求头中一个Accept-Language 参数来识别会更好。

1.创建各个语言文件

在resources下新建一个文件夹i18n,并在其下创建四个properties文件,格式为 messages_语言代码_国家代码,分别对应了 默认语言,英语, 繁体,日语
image.png

2. 设置语言文件中key-value

随便点击其中的一个properties,选择左下角的Resource Bundle,在里面添加相关属性,并设置中英文时的值,以及默认值
image.png

3. 配置文件修改我们文件所放位置

在主配置文件中指定我们国际化资源的位置

#配置自己的国际化文件位置
spring.messages.basename=i18n/login

image.png

4. 自定义MyLocaleResolver并注入

image.png

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 可以在连接上携带区域信息
 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String language = request.getHeader("Accept-Language");
        Locale locale = Locale.getDefault();
        if(StringUtils.isNotBlank(language)){
            String[] split = language.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

image.png


import com.sun.servicefeign.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

/**
 * 配置国际化语言
 *
 **/
@Configuration
public class LocaleConfig {

    /**
     * 默认解析器 其中locale表示默认语言
     */
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

5. 编写查询工具类

image.png

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

/**
 * @program: makefriends
 * @description:
 * @author: Mr.Wang
 * @create: 2022-04-02 14:58
 **/
@Component
public class MessageUtils {
    private static MessageSource messageSource;

    public MessageUtils(MessageSource messageSource) {
        MessageUtils.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        return get(msgKey, null);
    }

    /**
     * 传参获取国际翻译值 语言文件中使用{0} {1} 参数展位
     */
    public static String get(String msgKey, Object... var2) {
        try {
            return messageSource.getMessage(msgKey, var2, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return msgKey;
        }
    }
}

6. 测试

image.png
image.png
image.png

0

评论区