1. First, build the struts2 environment,
2. Create an action. Test i18n.
3. Below is a simple configuration of Struts. XML, which contains the configuration of the properties file in 2. One is global and the other is local,
<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype struts public "-// Apache Software Foundation // DTD struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts. devmode "value =" true "/> <! -- Local configuration --> <! -- <Constant name = "struts. Custom. i18n. Resources" value = "com/test/Action/i18n"> </constant> --> <! -- Global configuration --> <! --> <Constant name = "struts. custom. i18n. resources "value =" test "> </constant> <package name =" default "namespace ="/"extends =" struts-Default "> <action name =" "class = ""com. test. action. i18naction "> <result>/index. JSP </result> </Action> </package> </struts>
4. According to the struts2 configuration, the plug-in is a configuration file named test_en_us.properties and test_zh_cn.properties,
The content in test_en_us.properties is: Hello = Hi, hello
The content in test_zh_cn.properties is: Hello = \ u4f60 \ u597d (Note: This is compiled by encoding. You can also use the properties of myeclipse to automatically edit the conversion ).
5. The following is the JSP display page: I have sorted out the following implementation methods,
<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% @ taglib prefix =" S "uri ="/Struts-tags "%> <% string Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML>
6. to switch between Chinese and English, add this sentence to the action.
Locale locale = new locale ("ZH", "cn"); // (this can be dynamically changed based on the value you sent) servletactioncontext. getrequest (). getsession (). setattribute ("ww_trans_i18n_locale", locale );
7. Basically, dynamic link switching can be implemented in both Chinese and English. However, there is still a small problem that needs to be solved. That is, you need to click 2 Chinese to switch to Chinese,
The same is true in English. How can this problem be solved?
8. It is actually very easy to solve the problem. Just configure a fitler Interceptor. It is best to configure this interceptor in front of the struts2 interceptor,
The content of the interceptor is:
String local=arg0.getParameter("local"); if(local!=null){ String loc[]=local.split("_"); Locale locale=new Locale(loc[0],loc[1]); ((HttpServletRequest)arg0).getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale); } arg2.doFilter(arg0, arg1);
In this way, you can dynamically switch between Chinese and English.