Recently, zh_hans_cn was introduced to solve the problem of Chinese locale changes in Windows 8. sites that have already supported Chinese languages cannot work normally.
Of course, you can add a resource file to support the new locale, but different browsers are involved. In fact, this support can only take effect for ie10 or ie11.
To solve this problem, I used a procedural approach to maintain the original resource file and convert locale in the program. Because the sites are composed of multiple technical frameworks, you need to know the technical solutions of multiple frameworks before solving them.
What is internationalization?
Internationalization is a way to design and manufacture products that are easy to adapt to the requirements of different regions. It requires that elements related to the language, country, and culture of all regions be extracted from the product. In other words, when the functions and code design of an application are considered to run in different regions, the Code simplifies the production of different local versions. The process of developing such a program is called internationalization.
In other words, you only need to change the language settings of the browser on some websites to see the interface of different language versions without modifying a line of code.
1. jstl Internationalization
Before various frameworks are available, J2EE internationalization projects usually adopt the following practices:
1.1 JSP Environment
First write a messages. zh_cn.properties file, in the class-path is/WEB-INF/classes welcome = welcome then use native2ascii.exe to convert it to welcome = \ Huan \
Define the messages file in Web. xml
<Context-param>
<Param-Name> javax. servlet. jsp. jstl. FMT. localizationcontext </param-Name>
<Param-value> messages </param-value>
</Context-param>
Finally, use
<% @ Taglib uri = "http://java.sun.com/jstl/fmt" prefix = "FMT" %>
<FMT: Message key = "welcome"/>
If there are multiple resource bundle files, you must use <FTM: bundle> to define them in JSP.
1.2 pure Java environment
Resourcebundle RB = resourcebundle. getbundle ("messages ");
String welcome = RB. getstring ("welcome ");
2) Spring Enhancement
Spring adds the messagesource concept. One is that applicationcontext will act as a Singleton, instead of initializing resourcebundle every time i18 is used. The other is that it can represent multiple resource bundle.
Add the following nodes to the definition file of applicationcontext:
<Bean id = "messagesource" class = "org. springframework. Context. Support. resourcebundlemessagesource">
<Property name = "basename" value = "messages"/>
</Bean>
In the pure Java environment. Context. getmessage ("welcome", null, locale. China)
In the JSP environment, when the Controller calls jstl viewresolver and then calls JSP, <FMT: Message> continues to play its role.
Therefore, samples such as appfuse are defined in the appfuse-servlet.xml as a <messagesource>.
3)StrutsPractices
3.1.struts1 and struts2 configurations in the configuration file.
|
Struts1 |
Struts2 |
Struts-config.xml |
<Message-resources parameter = "XXX. XX. XXX. applicationresources"/> |
|
Struts. xml |
|
<Constant name = "struts. Custom. i18n. Resources" value = "message"> </constant> |
3.2.struts1 and struts2 are displayed on the page.
|
Struts1 |
Struts2 |
Index. jsp |
<Bean: Message key = "username"/> |
|
Index. jsp |
|
<S: Text name = "username"> </S: Text> |
3.3.struts1 and struts2 use Java code to control Internationalization
Idea: first obtain the relevant language information, then set it to the environment, and finally obtain the relevant resource file information through resourcebundle.
A: related code of struts1
String currentlocale = request. getlocale (). tostring (); // The default browser language request. getsession (). setattribute (globals. locale_key, currentlocale); // Add the language to the environment. // use resourcebundle to obtain the resource file resourcebundle = resourcebundle. getbundle ("applicationresources", currentlocale ); |
B: related code of struts2
Locale currentlocale = request. getlocale (). tostring (); // obtain the session in the local language. setattribute ("ww_trans_i18n_locale", localizedtextutil. localefromstring (currentlocale, null); // import the language to the environment. // use resourcebundle to obtain the resource file resourcebundle = resourcebundle. getbundle ("applicationresources", currentlocale ); |
3.4.struts1 instance
Implementation idea: When we select Chinese or English on the page, the relevant language variables will be stored in the cookie (which language can be obtained in the filter ), write a filter (localefilter) to filter the request information of each page. In localefilter, we first determine whether the cookie has an agreed cookie value. If so, set the language to the environment, if not, you can get the default language of the browser and then set it to the environment (the locale priority set by the user on the screen is higher than the locale obtained by the browser setting language ).
Preparations:
- Create the resource file applicationresources_en_us.properties and applicationresources_zh_cn.properties.
- Create a localefilter and configure localefilter to Web. xml.
- Configure in struts-config.Xml
<message-resources parameter="ApplicationResources" /> |
- Create an index. jsp to switch between Chinese and English.
Implementation:
A. Created resource file:
B. Web. xml configuration:
<filter><filter-name>localeFilter</filter-name><filter-class>xx.xx.xx. LocaleFilter</filter-class></filter><filter-mapping><filter-name>localeFilter</filter-name><url-pattern>/*</url-pattern><dispatcher>REQUEST</dispatcher><dispatcher>FORWARD</dispatcher></filter-mapping> |
C. configuration in the struts-config.xml:
<message-resources parameter="ApplicationResources"/> |
D. Create the index. jsp page and then internationalize it.
Index. jsp page HTML code
<SPAN class = "rk_qh"> <a class = "rk_qhuan" onclick = "clicklan ();"> <span style = "margin: 0 2px; ">$ {LAN} </span> </a> <ul id =" ul_lans "class =" chinese_english_huan "onmouseover =" clicklan (); "onmouseout =" hidelan (); "> <li> <a href =" javascript: ages (\ 'zh _ Cn \ ') "> Chinese (simplified) </a> </LI> <li class = "rk_topborder_n"> <a href = "javascript: ages (\ 'en _ us \') "> English </a> </LI> </ul> </span> |
Index. jsp page JavaScript Method
Function programming ages (LAN) {var cookiespath = "/"; // path var cookiesdomain = ".xxx.com"; // set valid urldocument. cookie = "xxx_language =" + LAN + "; Path =" + cookiespath + "; domain =" + cookiesdomain; // write the information to the location in the cookie. reload (); // refresh this page to switch internationally} |
E. localefilter (filter) Code
Package COM. ruanko. webapp. filter; import Org. apache. struts. globals; import Org. springframework. web. filter. onceperrequestfilter; import javax. servlet. filterchain; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import Java. io. ioexception; import Java. util. locale; import Java. util. resourcebundle; import javax. servlet. HTTP. cooki E; public class localefilter extends onceperrequestfilter {public static final string Chineselanguage = "Chinese (simplified)"; public static final string Englishlanguage = "English"; @ suppresswarnings ("unchecked ") public void dofilterinternal (httpservletrequest request, httpservletresponse response, filterchain chain) throws ioexception, servletexception {/* Filter Implementation ideas: (1) determine whether there is a value in cookies, if there is a value, the cookies are worth a locale (2) Co If Okies has no value, the browser displays */locale currentlocale = NULL according to the default language of the browser; // defines the region information of the language string Language = NULL; // The language cookiescookie written on the client page [] cookies = request. getcookies (); If (cookies! = NULL) {for (Cookie: cookie) {If (cookie. getname (). equals ("xxx_language") {Language = cookie. getvalue (); // determines and sets whether there is a value in cookies. }}} Try {/*** 1. if there is a value in cookies (the precondition is that the language passed from the page is empty before entering the following logic) */If (language! = NULL) {If ("zh_cn ". equals (language) {// if the language in cookies is Chinese currentlocale = new locale ("ZH", "cn"); Language = "zh_cn"; request. getsession (). setattribute ("Lan", Chineselanguage);} else if ("en_us ". equals (language) {// if the language in cookies is English currentlocale = new locale ("en", "us"); Language = "en_us"; request. getsession (). setattribute ("Lan", Englishlanguage);} else {currentlocale = new locale ("ZH", "cn"); Language = "zh_cn"; request. getsession (). setattribute ("Lan", Chineselanguage) ;}}/*** language: if no language is passed or the value in cookies is displayed, */else {string defaultlanguage = request is displayed based on the default language of the browser. getlocale (). tostring (); // The default browser language if (defaultlanguage. equals ("en_us") {currentlocale = new locale ("en", "cn"); Request. getsession (). setattribute ("Lan", Englishlanguage);} else {currentlocale = new locale ("ZH", "cn"); Request. getsession (). setattribute ("Lan", Chineselanguage) ;}} catch (exception e) {e. printstacktrace ();} finally {// Finally, put the set environment class in the session to request. getsession (). removeattribute (globals. locale_key); Request. getsession (). setattribute (globals. locale_key, currentlocale);} chain. dofilter (request, response );}} |
F. Obtain the value of the resource file in Java code.
Locale locale = (locale) request. getsession (). getattribute (globals. locale_key); resourcebundle = resourcebundle. getbundle ("applicationresources", locale); string course = resourcebundle. getstring ("coe_course ");2. SummaryBecause the project's international subjects still use the jstl solution to obtain the settings of the corresponding resource files, but also use some taglibs of struts1, and use the default locale on the server for some plug-ins. solution: 1> for jstl settings, use a servletfilter to implement locale conversion. Public class localeservletfilter implements filter {@ override public void destroy () {// todo auto-generated method stub} @ override public void dofilter (servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {locale sesionlocale = request. getlocale (); string locstr = sesionlocale. tostring (); locale proloc = locfromstring (locstr); localesetid. setloca Le (proloc); Request. setattribute ("javax. servlet. JSP. jstl. FMT. fallbacklocale ", proloc. tostring (); Request. setattribute ("javax. servlet. JSP. jstl. FMT. locale ", proloc. tostring (); httpservletrequest hprequest = (httpservletrequest) request; httpservletresponse hpresponse = (httpservletresponse) response; hprequest. setcharacterencoding ("UTF-8"); httpsession session = hprequest. getsession (); config. set (SE Ssion, config. fmt_locale, proloc); Session. removeattribute (globals. locale_key); Session. setattribute (globals. locale_key, proloc); chain. dofilter (hprequest, hpresponse);} public locale locfromstring (string locale) {string parts [] = locale. split ("_"); If (parts. length = 1) return New locale (parts [0]); else if (parts. length = 2) {If (parts [1]. equalsignorecase ("Hans") {return New locale (parts [0], "Cn");} else {return New locale (parts [0], parts [1]);} else if (parts. length = 3 & parts [1]. equalsignorecase ("Hans") {return New locale (parts [0], parts [2]);} else return New locale (parts [0], parts [1], parts [2]);} 2> for the locale setting of struts1 and taglib/** i18n the title */Public String gettitle () {If (islocalizedtitle) {locale userlocale = requestutils. getuserlocale (httpservletrequest) pageco Ntext. getrequest (), null); httpservletrequest Req = (httpservletrequest) pagecontext. getrequest (); locale localeprocessed = locfromstring (req. getlocale (). tostring (); req. getsession (). setattribute (globals. locale_key, localeprocessed); pagecontext. setattribute (globals. locale_key, localeprocessed); try {String title = tagutils. getinstance (). message (pagecontext, null, globals. locale_key, super. gettitle (); Return title;} catch (jspexception e) {log. debug (E); // do not localize then} return Super. gettitle () ;}3> for the default locale problem in Plug-in or server code. In the previous servletfilter, I set a global variable. on the server side, if you need to use locale to call the following method. LocaleSetId.getLocale();
|