convert.jsp
<h1>${displayLang}</h1> <form action="convert!getLangAndDisplay.action" method="post"> Language: <input type="radio" value="zh_TW" name="loc" checked="checked" />Chinese Traditional <input type="radio" value="en_US" name="loc" />English <input type="submit" value="display"> </form>
struts.xml
<constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.custom.i18n.resources" value="TestLanguage" /> <constant name="struts.devMode" value="true" /> <package name="basicstruts2" extends="struts-default" namespace="/struts2"> <action name="convert" class="convert.ConvertAction"> <result name="success">/struts2/convert.jsp</result> <result name="input">/struts2/fail.jsp</result> </action> </package>
ConvertAction.java
private Locale loc; //setter即可 public String getLangAndDisplay() { HttpServletRequest request = ServletActionContext.getRequest(); String lang = LocalizedTextUtil.findDefaultText("test.lang", this.loc); request.setAttribute("displayLang", lang); System.out.println("loc=" + loc); return ActionSupport.SUCCESS; }
TestConvert.java,StrutsTypeConverter是Struts2內鍵的class
public class TestConvert extends StrutsTypeConverter { @Override public Object convertFromString(Map arg0, String[] arg1, Class arg2) { Locale loc = null; if (arg2.equals(Locale.class)) { String lang[] = arg1[0].split("_"); loc = new Locale(lang[0], lang[1]); } return loc; } @Override public String convertToString(Map arg0, Object arg1) { return null; } }
xwork-conversion.properties,一定要這樣取
java.util.Locale=convert.TestConvert
TestLanguage_zh_TW.properties
test.lang=\u6B61\u8FCE\uFF01
TestLanguage_en_US.properties
test.lang=welcome!
可以參考這裡
xwork-conversion.properties可以改成不是全域的,在Action同層建一個ConvertAction-conversion.properties,因為我的Action叫ConvertAction
內容改為
loc=convert.TestConvert
loc是ConvertAction的變數名稱
這篇文章有說properties的執行順序,我試不出來,只有用最後一招的global有用,這裡用的就是global
沒有留言:
張貼留言