Java實現多語言切換
阿新 • • 發佈:2018-12-29
在一個專案中涉及到中英文版本,一般在登入頁或者首頁的時候會有中英文連線
這個連線可以這樣寫:
前臺讀取多語言:<div class="flag"> <s:url id="localeUsUrl" action="localeUs"></s:url> <s:url id="localeCnUrl" action="localeCn"></s:url> <a class="en" href="${localeUsUrl }"><s:property value="getText('language.english')" /></a> <a class="ch" href="${localeCnUrl }"><s:property value="getText('language.chinese')" /></a> </div>
其中 <s:property value="getText">標籤是struts自帶的可以獲得properties裡的鍵和值
當選中文時 後臺action如下
session.clear();
session.put("WW_TRANS_I18N_LOCALE", Locale.CHINA);
ActionContext.getContext().setLocale(Locale.CHINA);
英文:後臺讀取多語言:session.clear(); session.put("WW_TRANS_I18N_LOCALE", Locale.US); ActionContext.getContext().setLocale(Locale.US);
當我們從後臺想輸出一個提示資訊時,首先要獲取當前Local環境
Locale currentLocale = Locale.getDefault();
currentLocale 分en,zh等
讀取properties的方法為:
try { InputStream is = Test.class.getClassLoader().getResourceAsStream(propertiesName); properties.load(is); value = properties.getProperty(key); }
返回這個String 型的value即可