Java web--internationalization i18n

Source: Internet
Author: User
Tags dateformat i18n locale stringbuffer

1. What is internationalization and localization:

I. Localization: When a software is used in a country or region, it uses the language, numbers, currency, date and other habits of that country or region.
II. Internationalization: Software development enables it to support localized applications in multiple countries and regions. Enables application software to adapt to language and cultural customs in multiple regions
Iii. Local sensitive data: data that changes with user region information is called local information sensitive data. Data such as numbers, currency, date, time, etc.

2. Related APIs:

I. DateFormat and Simpledateformat√.
II. NumberFormat
III. Messageformat
Iv. ResourceBundle
V. Locale

3. About Internationalized Resource documents:

I. Properties file Format
II. Must provide the base name. properties File and base name _ language code _ Country code. Properties File
III. resource files of the same base name must have the same key.
Iv. the non-ASC code may need to be converted to ASC using the Native2ascii tool.

4. Internationalization of the WEB

I. You can use Request.getlocale () to get the Locale object
II. You can use the JSTL FMT label to complete internationalization. This is done using the tags provided by the framework later.
Iii. to achieve the "Chinese" "English" switch:

> offers two ultra-simple. Carry different values of variables
> Determine the corresponding Locale object based on the value of the variable
> Put Locale objects into session
> binds the resource file for the Locale.

Iv. Other FMT tags can refer to examples in Standard-examples.war.

5. Code Area

 Packagecom.atguigu.i18n;ImportJava.text.DateFormat;ImportJava.text.MessageFormat;ImportJava.text.NumberFormat;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.Locale;ImportJava.util.ResourceBundle;Importorg.junit.Test; Public classI18ntest {/*@Test public void TestMessageFormat2 () {String str = "Date: {0}, Salary: {1}";        locale locale = Locale.china;        Date date = new Date ();                Double sal = 12345.12;        StringBuffer result = new StringBuffer ();                FieldPosition fieldposition = new FieldPosition (0);        Messageformat Messageformat = new Messageformat (str, locale);                Messageformat.format (date, result, fieldposition);     SYSTEM.OUT.PRINTLN (result); }    */        /*** ResourceBundle: Resource Bundle class. * * 1. A corresponding resource file is required under the classpath: Basename.properties.     Where BaseName is the base name. * 2. You can use the base name _ language code _ Country code. Properties to add resource files for different countries or regions. I18n_zh_cn.properties * 3.      The key for all resource files that require the same base name must be exactly the same. * 4. You can use the NATIVE2ASCII command to get an ASC code for a Chinese character pair. Eclipse built-in tool * 5. You can call ResourceBundle's Getbundle (base name, Locale instance) to get the ResourceBundle object * 6.      You can call ResourceBundle's getString (key) to get the value of the value string for the resource file. * 7.      Combined with DateFormat, NumberFormat, Messageformat can achieve internationalization. *      */@Test Public voidTestresourcebundle () {locale locale=Locale.china; ResourceBundle ResourceBundle= Resourcebundle.getbundle ("i18n", Locale); //Date WagesSystem.out.println (resourcebundle.getstring ("date")); System.out.println (Resourcebundle.getstring ("Salary")); String Datelabel= Resourcebundle.getstring ("date"); String Sallabel= Resourcebundle.getstring ("Salary"); String Str= "{0}:{1}, {2}:{3}"; Date Date=NewDate (); DoubleSal = 12345.12; DateFormat DateFormat=dateformat.getdateinstance (dateformat.medium, locale); String Datestr=Dateformat.format (date); NumberFormat NumberFormat=numberformat.getcurrencyinstance (locale); String Salstr=Numberformat.format (SAL); String result=Messageformat.format (str, Datelabel, DATESTR, Sallabel, SALSTR); //Date: 2018-1-18, Salary: ¥12,345.12System.out.println (Result); }        /*** Messageformat: Can format pattern String * Pattern string: string with placeholder: "Date: {0}, Salary: {1}" * Can be formatted using the Format method of the pattern string. /c2>*/@Test Public voidTestmessageformat () {String str= "Date: {0}, Salary: {1}"; Locale Locale=Locale.china; Date Date=NewDate (); DoubleSal = 12345.12; DateFormat DateFormat=dateformat.getdateinstance (dateformat.medium, locale); String Datestr=Dateformat.format (date); NumberFormat NumberFormat=numberformat.getcurrencyinstance (locale); String Salstr=Numberformat.format (SAL); String result=Messageformat.format (str, DATESTR, SALSTR); //date:2018-1-18, salary:¥12,345.12 defining information formatsSystem.out.println (Result); }        /*** NumberFormat: Formatting numbers to numeric strings, or tool classes for currency strings * 1. Get the NumberFormat object by factory method * Numberformat.getnumberinstance (LO Cale); A string formatted as a number * numberformat.getcurrencyinstance (locale); The format is the currency of the string * * 2. Formatted with the Format method * 3.      Parses a string into a number type by using the Parse method. */@Test Public voidTestnumberformat ()throwsparseexception{DoubleD = 123456789.123d; Locale Locale=locale.france; NumberFormat NumberFormat=numberformat.getnumberinstance (locale); String Str=Numberformat.format (d); //123 456 789,123System.out.println (str); NumberFormat NumberFormat2=numberformat.getcurrencyinstance (locale); STR=Numberformat2.format (d); //123 456 789,12€System.out.println (str); STR= "123 456 789,123"; D=(Double) numberformat.parse (str); //1.23456789123E8System.out.println (d); STR= "123 456 789,12€"; D=(Double) numberformat2.parse (str); //1.2345678912E8System.out.println (d); } @Test Public voidTESTDATEFORMAT2 ()throwsparseexception{String str= "1990-12-12 12:12:12"; DateFormat DateFormat=NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); //Wed Dec 00:12:12 CST 1990Date Date =dateformat.parse (str);     SYSTEM.OUT.PRINTLN (date); }        /*** DateFormat: A tool class that formats dates.      * Dateformate itself is an abstract class. * * 1. If you only want to convert a Date object to a string by DateFormat, you can get DateFormat Object * 2 through DateFormat's factory method. You can get a DateFormat object that only formats Date: getdateinstance (int style, Locale alocale) * 3. You can get the DateFormat object that only formats time: gettimeinstance (int style, Locale alocale) * 4. You can get DateFormat objects that both format Date and format time: * getdatetimeinstance (int datestyle, int timestyle, Locale alocale) * 5. Where style can be evaluated as: DATEFORMAT constant: Short, MEDIUM, LONG, full. Locale is the locale object representing the national region * 6.      Formats a Date object into a string by using the format method of DateFormat. * * 7.      If you have a string, how do you parse it into a Date object?      * I. Create DateFormat object: Create DateFormat Subclass SimpleDateFormat Object * SimpleDateFormat (String pattern). * Where pattern is a date, the format of time, for example: Yyyy-mm-dd HH:MM:SS * ii.       Call DateFormat's Parse method to parse the string into the Date object. *      */@Test Public voidTestdateformat () {locale locale=Locale.china; Date Date=NewDate (); //Thu Jan 14:29:48 CST 2018System.out.println (date); //get DateFormat Object January 18, 2018 14:30:29DateFormat DateFormat =dateformat.getdatetimeinstance (Dateformat.long, Dateformat.medium, locale); String Str=Dateformat.format (date);             System.out.println (str); }    /*** Locale:java represents the country or region of the class.     Many constants are available in the JDK.      * can also be created through the Locale (Languagecode, CountryCode) method can be obtained through the Request.getlocale () way in the WEB application. */@Test Public voidTestlocale () {locale locale=Locale.china; //China enSystem.out.println (Locale.getdisplaycountry ());         System.out.println (Locale.getlanguage ()); //United States enLocale =NewLocale ("en", "US");        System.out.println (Locale.getdisplaycountry ());     System.out.println (Locale.getlanguage ()); }    }
i18ntest
date=datesalary=salary
i18n_en_us.properties
date=\u65e5\u671fsalary=\u5de5\u8d44
i18n_zh_cn.properties
date=datesalary=salary
i18n.properties
<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "Webapp_ ID "version=" 2.5 ">  <display-name>i18n</display-name>  <welcome-file-list>    < welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default. html</ welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file> default.jsp</welcome-file>  </welcome-file-list></web-app>
Web. XML
<% @pageImport= "Java.util.Locale"%><% @pageImport= "java.util.Date"%><%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding= "UTF-8"%><%@ taglib prefix= "FMT" uri= "http://java.sun.com/jsp/jstl/fmt"%><%@ taglib prefix= "C" uri= " Http://java.sun.com/jsp/jstl/core "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Date Date=NewDate (); Request.setattribute ("Date", date); Request.setattribute ("Salary", 12345.67); %> <%--<fmt:bundle basename= "i18n" > <fmt:message key= "Date" ></fmt:message>:         <fmt:formatdate value= "${date}"/>,        <fmt:message key= "Salary" ></fmt:message>:        <fmt:formatnumber value= "${salary}" ></fmt:formatNumber> </fmt:bundle> <br><br>--% > <%String Code= Request.getparameter ("code"); if(Code! =NULL){            if("en". Equals (code)) {Session.setattribute ("Locale", locale.us); }Else if("zh". Equals (code)) {Session.setattribute ("Locale", Locale.china); }                    }    %> <c:ifTest= "${sessionscope.locale! = null}" > <fmt:setlocale value= "${sessionscope.locale}"/> </c:if> <fmt:setbundle basename= "i18n"/> <fmt:message key= "Date" ></fmt:message>:     <fmt:formatdate value= "${date}" datestyle= "full"/>,    <fmt:message key= "Salary" ></fmt:message>:    <fmt:formatnumber value= "${salary}" type= "Currency" ></fmt:formatNumber> <br><br> <a href= "index.jsp?code=en" >English</a> <a href= "Index.jsp?code=zh" > Chinese </a> </body></ Html>
index.jsp

Java web--internationalization i18n

Related Article

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.