首页 > 编程语言 > 详细

Spring中后台字符串国际化

时间:2014-09-18 18:29:04      阅读:213      评论:0      收藏:0      [点我收藏+]

  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中后台字符串国际化

原文:http://www.cnblogs.com/ScorchingSun/p/3979418.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!