java国际化工具类
创建工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| import org.apache.commons.lang3.ObjectUtils;
import java.util.*;
public class I18nUtils {
private static final String REOURCES_PATH = "i18n/resource";
private static List<String> msgResources = Arrays.asList(REOURCES_PATH);
public static String getString(String environment, String key) { Locale locale = getLocale(environment); return getMessage(key, null, locale); }
public static String getString(String key, Map contextMap) { String environment = SecurityUtils.getLanguage(); Locale locale = getLocale(environment); return getMessage(key, contextMap, locale); }
public static Locale getLocale(String environment) { Locale locale; if (StringUtils.equalsIgnoreCase(environment, "CN")) { locale = Locale.CHINA; } else if (StringUtils.equalsIgnoreCase(environment, "EN")) { locale = Locale.US; } else { locale = Locale.CHINA; } return locale; }
public static String getMessage(String msgKey, Map mapParams, Locale locale) { if (StringUtils.isEmpty(msgKey)) { return ""; } if (null == locale) { locale = getLocale(null); } String resultMsg = msgKey; for (String msgResource : msgResources) { ResourceBundle bundle = ResourceBundle.getBundle(msgResource, locale); String result = null; try { result = bundle.getString(msgKey); } catch (Exception e) { e.printStackTrace(); } if (StringUtils.isNotBlank(result)) { resultMsg = result; break; } } return replaceParams(resultMsg, mapParams);
}
public static String getSystemString(String key) { String environment = SecurityUtils.getLanguage(); Locale locale = getLocale(environment); return getMessage(key, null, locale); }
public static String replaceParams(String message, Map<String, Object> paramMap) { if (ObjectUtils.isNotEmpty(paramMap)) { for (String key : paramMap.keySet()) { message = StringUtils.replaceAll(message, "${" + key + "}", StringUtils.replaceNull(paramMap.get(key))); } } return message; }
}
|
配置资源文件
在resources资源文件夹下新建i18n资源文件夹,创建resource_en_US.properties,和resource_zh_CN.properties配置文件,配置文件命名格式:自定义名_语言代码_国别代码.properties
语言代码和国别代码可以在java.util.Locale类中查找例如中文:
资源文件命名为:resource_en_US.properties
中文资源文件的中文需要转为unicode再往配置中写入,否则会导致无法解析