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);

总结

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

相关文章

  • Java中动态设置JVM参数的方法总结

    Java中动态设置JVM参数的方法总结

    通过动态设置JVM参数,开发者可以更有效地管理资源使用和优化性能,本文将详细阐述如何在Java中动态设置JVM参数,感兴趣的小伙伴可以了解下
    2024-12-12
  • Java枚举学习之定义和基本特性详解

    Java枚举学习之定义和基本特性详解

    枚举是JAVA 5.0后增加的一个重要类型。可以用来表示一组取值范围固定的变量。本文将通过示例为大家详细讲解枚举的定义和基本特性,感兴趣的可以了解一下
    2022-08-08
  • 详解application.properties和application.yml文件的区别

    详解application.properties和application.yml文件的区别

    这篇文章主要介绍了详解application.properties和application.yml文件的区别,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • Java堆&优先级队列示例讲解(下)

    Java堆&优先级队列示例讲解(下)

    这篇文章主要通过示例详细为大家介绍Java中的堆以及优先级队列,文中的示例代码讲解详细,对我们了解java有一定帮助,需要的可以参考一下
    2022-03-03
  • 教你利用springboot集成swagger并生成接口文档

    教你利用springboot集成swagger并生成接口文档

    有很多小伙伴不会利用springboot集成swagger并生成接口文档,今天特地整理了这篇文章,文中有非常详细的代码图文介绍及代码示例,对不会这个方法的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05
  • 一文带你彻底搞懂Lambda表达式

    一文带你彻底搞懂Lambda表达式

    这篇文章主要介绍了一文带你彻底搞懂Lambda表达式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Java方法重载实现原理及代码实例

    Java方法重载实现原理及代码实例

    这篇文章主要介绍了Java方法重载实现原理及代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • mybatisplus的逻辑删除过程

    mybatisplus的逻辑删除过程

    这篇文章主要介绍了mybatisplus的逻辑删除过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-08-08
  • springBoot热部署、请求转发与重定向步骤详解

    springBoot热部署、请求转发与重定向步骤详解

    这篇文章主要介绍了springBoot热部署、请求转发与重定向,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • SpringBoot中集成IP2Region实现高效IP地址地理位置查询

    SpringBoot中集成IP2Region实现高效IP地址地理位置查询

    IP2Region是一个高效的IP地址地理位置查询库,能够快速根据IP地址获取其地理位置信息,它支持IPv4和IPv6地址的查询,并提供多种缓存方式来优化查询性能,在这篇博客中,我们将介绍如何将IP2Region集成到SpringBoot项目中,实现IP地址的地理位置查询服务
    2025-12-12

最新评论