首页 > 代码库 > Spring中后台字符串国际化

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 {        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的字符串,会抛出异常。

Spring中后台字符串国际化