Procedural processing of Struts1 for zh_HANS_CN Internationalization

Source: Internet
Author: User
Tags locale setting

Procedural processing of Struts1 for zh_HANS_CN Internationalization
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


Javax. servlet. jsp. jstl. fmt. localizationContext
Messages

Finally, use
<% @ Taglib uri = "http://java.sun.com/jstl/fmt" prefix = "fmt" %>

If there are multiple Resource Bundle files, use Defined.

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:



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, Will continue to play its role.

Therefore, samples such as appfuse are defined in a appfuse-servlet.xml .



3)StrutsPractices

3.1.Struts1 and Struts2 configurations in the configuration file.

Struts1 Struts2
Struts-config.xml
Struts. xml

3.2.Struts1 and Struts2 are displayed on the page.

Struts1 Struts2
Index. jsp
Index. jsp

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
          
    Create an index. jsp to switch between Chinese and English.

    Implementation:

    A. Created resource file:

    B. web. xml configuration:

          
           
            localeFilter
           
           
            xx.xx.xx. LocaleFilter
           
          
          
           
            localeFilter
           
           
            /*
           
           
            REQUEST
           
           
            FORWARD
           
          

    C. configuration in the struts-config.xml:

          

    D. Create the index. jsp page and then internationalize it.

    Index. jsp page html code

    $ {Lan}
          
          
    • Chinese (simplified)
    • English

    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: 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 = 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();



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.