zoukankan      html  css  js  c++  java
  • java项目国际化ResourceBundleMessageSource

    最近项目需要国际化,一般常见的方式就是采用配置文件话国际化。

    根据请求头传入不同的语言,返回不同的内容;

    自己搭建了一个模型,分如下几步:

    1.spring配置文件修改,定义国际化消息

    2.查找项目中需要返回到web的国际化内容,写到配置文件中

    3.处理国际化封装成一个工具类,在controller层 统一处理。

    国际化需要注意,如果调用方未传language,系统需要默认一个,最好写在配置文件中,方便随时修改,用 @value注入到国际化工具类中。

    一 :Spring配置文件

      <!-- 定义国际化消息-->
        <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
            <!-- 其中basename用来指定properties文件的通用名
                  如实例中的messages_en.properties,messages_ja.properties通用名都是messages
             -->
            <property name="basename" value="messages"/>
            <property name="useCodeAsDefaultMessage" value="true" />
            <property name="defaultEncoding" value="UTF-8"/>
            <property name="cacheSeconds" value="100"></property>
    
        </bean>
    View Code

    二:配置文件国际化,如下图

     三:工具类:

     1 @Service
     2 public class ResponseUtil {
     3 
     4     @Value(value = "${default.xLanguage}")
     5     public String language;
     6 
     7     public  String getMessage(String xLanguage, Error error, String className){
     8 
     9         if(StringUtils.isEmpty(xLanguage)){
    10             xLanguage = language;
    11         }
    12         if(null==error){
    13             return "请求成功";
    14         }
    15         /***此处根据不同的code获取国际化资源**/
    16        
    17 
    18         ResourceBundle resourceBundle = null;
    19         switch (xLanguage){
    20             case "en-US":
    21                 resourceBundle = ResourceBundle.getBundle("messages", Locale.US);
    22                 break;
    23             case "zh-CN":
    24                 resourceBundle = ResourceBundle.getBundle("messages", Locale.SIMPLIFIED_CHINESE);
    25                 break;
    26         }
    27         if(null==resourceBundle){
    28             return null;
    29         }
    30 
    31         return resourceBundle.getString(messageKey);
    32     }
    33 
    34 
    35     }
    36 }    
    View Code

    PostMan模拟后,返回结果成功。

    ==========================================================================           如果您觉得这篇文章对你有帮助,可以【关注我】或者【点赞】,希望我们一起在架构的路上,并肩齐行
    ==========================================================================
  • 相关阅读:
    先装.NET SDK 后装IIS导致的错误
    proc
    C# FTP上传
    English Word
    Window服务程序
    DataView排序 疑惑
    移除字符串末尾制定个数字符
    树状列表
    updatepanel 中按钮下载文件出错解决
    如何删除vs最近打开的项目
  • 原文地址:https://www.cnblogs.com/amberJava/p/12362655.html
Copyright © 2011-2022 走看看