springboot如何实现国际化配置

 更新时间:2023年06月15日 14:20:39   作者:修行者Java  
这篇文章主要介绍了springboot如何实现国际化配置问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

springboot国际化配置

1.在yml文件的spring下加入下面代码

 messages:
	encoding: UTF-8
    basename: i18n/messages
    cache-second: 3600

2.在resource下创建i18n文件夹

(internationalization国际化,共18个字母简称i18n),

里面创建messages.properties(默认文件,非中、英文时读取)

  • messages_en.properties(英文)
  • messages_zh.properties(中文)


这是我用到的内容,可以参考下格式

英文:

NotEmpty=The input cannot be null
PhoneNotEmpty=The cell phone number cannot be empty
EmailNotEmpty=The mailbox cannot be empty
CodeNotEmpty=Verification code cannot be empty
ResendCode=Please resend the verification code
PhoneRegistered=The phone number has been registered
EmailRegistered=Email registered
PhoneNotRegistered=The phone number is not registered
EmailNotRegistered=Email not registered
CodeIncorrect=Verification code is incorrect
RegisterError=Registration failed. Please try again
AuthError=Authorization failed. Please try again
OperationError=Operation failed, please try again
BindingError=Binding failed, please try again
PhoneNotExist=The cell phone number does not exist
EmailNotExist=Email does not exist
PasswordError=Password Error
AccountFrozen=The account has been frozen, please contact customer service
AccountNotAudit=The account has not been audited, please contact customer service
SendError=Failed to send. Please try again
DownloadError=Download failed, please try again
DeleteError=Delete failed, please try again
RetrieveError=Retrieve failed, please try again
UpdateError=Modification failed, please try again
OriginalPasswordError=The original password is incorrect
ArticleNotExist=There is no announcement
UploadError=Upload failed. Please try again
MessageError=Message failed, please try again
ReplyError=Reply failed, please try again
RoomEntryError=Room entry failed. Please try again
RoomExitError=Room exit failed. Please try again
CreateRoomError=Studio creation failed. Please try again

中文:

  • NotEmpty=输入不能为空
  • PhoneNotEmpty=手机号不能为空
  • EmailNotEmpty=邮箱不能为空
  • CodeNotEmpty=验证码不能为空
  • ResendCode=请重新发送验证码
  • PhoneRegistered=手机号已注册
  • EmailRegistered=邮箱已注册
  • PhoneNotRegistered=手机号未注册
  • EmailNotRegistered=邮箱未注册
  • CodeIncorrect=验证码不正确
  • RegisterError=注册失败,请重试
  • AuthError=授权失败,请重试
  • OperationError=操作失败,请重试
  • BindingError=绑定失败,请重试
  • PhoneNotExist=手机号不存在
  • EmailNotExist=邮箱不存在
  • PasswordError=密码错误
  • AccountFrozen=账号已被冻结,请联系客服
  • AccountNotAudit=账号未审核,请联系客服
  • SendError=发送失败,请重试
  • DownloadError=下载失败,请重试
  • DeleteError=删除失败,请重试
  • RetrieveError=密码找回失败,请重试
  • UpdateError=更新失败,请重试
  • OriginalPasswordError=原密码错误
  • ArticleNotExist=没有此公告
  • UploadError=上传失败,请重试
  • MessageError=留言失败,请重试
  • ReplyError=回复失败,请重试
  • RoomEntryError=房间进入失败,请重试
  • RoomExitError=房间退出失败,请重试
  • CreateRoomError=房间创建失败,请重试

我这里直接写的是中文,csdn有很多版本,有的是ascii码,看个人喜好。

如果后面出现中文乱码情况,修改下这里:

3.后台公共方法

package com.es.api.modules.common.controller;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
@Controller
public class I18nController {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(I18nController.class);
    private MessageSource messageSource;
    /**
     * 初始化
     *
     * @return
     */
    private MessageSource initMessageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(3600);
        return messageSource;
    }
    /**
     * 设置当前的返回信息
     *
     * @param request
     * @param code
     * @return
     */
    public String getMessage(HttpServletRequest request, String code) {
        if (messageSource == null) {
            messageSource = initMessageSource();
        }
        String language = request.getHeader("language");
        //默认没有就是请求地区的语言
        Locale locale = null;
        if (language == null) {
            locale = request.getLocale();
        } else if ("en".equals(language)) {
            locale = Locale.ENGLISH;
        } else if ("zh".equals(language)) {
            locale = Locale.CHINA;
        }
        //其余的不正确的默认就是本地的语言
        else {
            locale = request.getLocale();
        }
        String result = null;
        try {
            result = messageSource.getMessage(code, null, locale);
        } catch (NoSuchMessageException e) {
            LOGGER.error("Cannot find the error message of internationalization, return the original error message.");
        }
        if (result == null) {
            return code;
        }
        return result;
    }
}

注意:我app传回的language是zh和en,所以我的properties文件命名直接是zh和en,这里注意下,不然错误提示是乱码

方法中调用:首先注入工具

@Autowired
private I18nController i18n;
@Autowired
private HttpServletRequest request;

然后

String message = i18n.getMessage(request, "NotEmpty");
return ResponseUtils.error(message);

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Spring温故而知新系列教程之AOP代理

    Spring温故而知新系列教程之AOP代理

    Spring AOP 是代理模式的应用,可以使用JDK提供的Proxy类或通过字节码增强来实现。下面这篇文章主要给大家介绍了关于Spring之AOP代理的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2018-05-05
  • java Swing实现选项卡功能(JTabbedPane)实例代码

    java Swing实现选项卡功能(JTabbedPane)实例代码

    这篇文章主要介绍了java Swing实现选项卡功能(JTabbedPane)实例代码的相关资料,学习java 基础的朋友可以参考下这个简单示例,需要的朋友可以参考下
    2016-11-11
  • java8 对象转Map时重复 key Duplicate key xxxx的解决

    java8 对象转Map时重复 key Duplicate key xxxx的解决

    这篇文章主要介绍了java8 对象转Map时重复 key Duplicate key xxxx的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • 使用Gson将字符串转换成JsonObject和JsonArray

    使用Gson将字符串转换成JsonObject和JsonArray

    这篇文章主要介绍了使用Gson将字符串转换成JsonObject和JsonArray,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • spring boot动态加载Echart饼状图

    spring boot动态加载Echart饼状图

    这篇文章主要为大家详细介绍了spring boot动态加载Echart饼状图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-12-12
  • Java源码解析重写锁的设计结构和细节

    Java源码解析重写锁的设计结构和细节

    这篇文章主要为大家介绍了Java源码解析重写锁的设计结构和细节,这小节我们以共享锁作为案列,自定义一个共享锁。有需要的朋友可以借鉴参考下
    2022-03-03
  • Java设计模式之java策略模式详解

    Java设计模式之java策略模式详解

    这篇文章主要介绍了Java经典设计模式之策略模式,简单说明了策略模式的概念、原理并结合实例形式分析了java策略模式的具有用法与相关注意事项,需要的朋友可以参考下
    2021-09-09
  • Kotlin 单例实例详解

    Kotlin 单例实例详解

    这篇文章主要介绍了Kotlin 单例实例详解的相关资料,需要的朋友可以参考下
    2017-06-06
  • java应用开发之JVM运行时内存分析

    java应用开发之JVM运行时内存分析

    这篇文章主要介绍了java应用开发之JVM运行时内存,文中附含图文示例内容分析非常简要,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2021-09-09
  • 讲解Java中的基础类库和语言包的使用

    讲解Java中的基础类库和语言包的使用

    这篇文章主要介绍了Java中的基础类库和语言包的使用,是Java入门学习中的基础知识,需要的朋友可以参考下
    2015-09-09

最新评论