Spring Boot项目国际化实现

1.创建国际化文件

由于SpringBoot默认就支持国际化的,所以我们只需要在resources文件夹 i18n下创建国际化配置文件即可,这里为了方便演示效果,咱么需要创建3个配置文件:

messages.properties 默认处理国际化的配置文件,要注意文件名是messages是固定的

messages_zh_CN.properties zh_CN 是中文简体

messages_en_US.properties en_US 是美国英语

Tips:

文件名也要以messages开头,如:messages_xxx.properties,如果不指定国际化语言则使用默认配置文件。

然后,在三个配置文件中分别添加配置属性。

在messages.properties添加中文配置信息,表示默认是使用的使用中文。

# 默认使用中文 i18n配置
username=云生

在messages_zh_CN.properties添加中文配置信息,表示默认是使用的使用中文。

# 使用中文i18n配置
username=云生

在messages_en_US.properties添加中文配置信息,表示默认是使用的使用中文。

# 使用美国英语i18n配置
username=yunshengsir

在这里插入图片描述

2.配置识别国际化文件

配置文件 application.properties 文件中配置 Message 路径,如下:

# Message路径
spring.messages.basename=i18n.messages

在这里插入图片描述

3. 案例代码

package com.lys.lys_admin_api.common.demon;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Locale;

/**
 * @Auther: liuysh
 * @Date: 2020/8/19 09:10
 * @Description: 国际化
 */
@RestController
public class I18nController {
    @Autowired
    private MessageSource messageSource;

    @GetMapping("i18n")
    public String i18n() {
        // 获取当前请求的区域Locale
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage("username", null, locale);
    }
}

4.请求

前后端分离的可以通过切面在请求中加入请求头,或者将lang存在session中的解决方案。

在请求头中,添加请求参数,注意参数的使用的-,而不是_下划线:

Accept-Language 语言设置成英文(en-US),效果如下,这个是在模拟用户使用的浏览器是语言,也就是用户是使用英语的

Accept-Language 语言设置成中文(注意参数是zh-CN),同上,这里模拟用户是使用中文作为浏览器的语言

猜你喜欢

转载自blog.csdn.net/liuyunshengsir/article/details/108093331