zoukankan      html  css  js  c++  java
  • Spring中后台字符串国际化

      1.在工程的资源文件夹(source folder)中建立三个properties文件:messages.properties(默认)、messages_zh_CN.properties(中文)、messages_en_US.properties(英文)。

      properties文件中的字符串资源采用键值对的格式填写信息,如下:

        HelloWorld=问候语:@0 问候时间:@1;

      2.获取国际化字符串的工具类 UniversalMsg

      

    package com.luxl.action;
    
    import java.util.Locale;
    import java.util.ResourceBundle;
    
    /**
     * @description 用于获取国际化字符串
     * @author luxl
     *
     */
    public class UniversalMsg {
        //下面中的参数messages是资源文件的起始字段,但要求资源文件在资源文件夹下,如果是在资源文件夹下的某个文件夹下,比如i18n,则参数值应该为为i18n/messages
        private static ResourceBundle rb_ch = ResourceBundle.getBundle("messages",Locale.CHINA);
        
        private static ResourceBundle rb_en = ResourceBundle.getBundle("messages", Locale.US);
        
        /**
         * @description 获取key的国际化字符串
         * @param locale 语种:中文(Locale.CHINA),英文(Locale.US)
         * @param key 要获取的字符串的key
         * @return
         * @throws Exception
         */
        public static String getString(Locale locale, String key) throws Exception{
            if(key!=null && (!key.trim().isEmpty())){
                if(locale.equals(Locale.CHINA)){
                    return rb_ch.getString(key);
                }else{
                    return rb_en.getString(key);
                }
            }else{
                return "";
            }
        }
        
        /**
         * @description 获取key的中文字符串
         * @param key
         * @return
         * @throws Exception
         */
        public static String getString(String key) throws Exception{
            if(key!=null && (!key.trim().isEmpty())){
                return rb_ch.getString(key);
            }else{
                return "";
            }
        }
    
    }

      3.应用举例:

    try {
        String us_msg;
        us_msg = UniversalMsg.getString(Locale.US,"HelloWorld");
        us_msg = us_msg.replaceAll("@0", helloWorld.getMsg());
        us_msg = us_msg.replaceAll("@1", Calendar.getInstance().getTime().toString());
        System.out.println(us_msg);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.out.println("error");
        e.printStackTrace();
    }  

    注:如果没有找到相对应key的字符串,会抛出异常。

  • 相关阅读:
    来自网络的双参求范围问题,没有单参求范围那么有套路!
    svn更改用户问题
    html控件中上传文件的技巧
    认识jsp
    dom4j 解析XML文件
    BaseDao优化
    JDBC连接数据库
    javascript常用函数
    jQuery formValidator(插件)
    javascriptDetect对象封装
  • 原文地址:https://www.cnblogs.com/ScorchingSun/p/3979418.html
Copyright © 2011-2022 走看看