Javaweb Enhancement: Internationalization

Source: Internet
Author: User
Tags dateformat i18n key string locale

Depending on the type of data, internationalization is divided into 2 categories: static data internationalization and dynamic Data internationalization.


static data, including text data such as "title", "User name", and "password".

Dynamic data, including data that can be dynamically generated by date, currency, and so on.


The Java.util.Locale and Java.util.ResourceBundle categories are involved in the international.


Java.util.Locale

A Locale object represents a specific geographical, political, or cultural region.

The locale object represents a certain geographical, political, and cultural area.


Java.util.ResourceBundle

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource Bundl E that's appropriate for the current user's locale. In this "You can write program code" is largely independent of the user's locale isolating most, if not all, of th e locale-specific information in resource bundles.

Resoucebundle, composed of two words resouce and bundles, together is the meaning of "resource bundle". Resoucebundle is a collection of different region (locale) resources, and as long as you provide a specific locale object to Resoucebundle, Resoucebundle will return the appropriate resources to you.

650) this.width=650, "src=" Http://s3.51cto.com/wyfs02/M01/83/A4/wKiom1d5hMbSGxdUAAAyLcgcnhk020.png "title=" internationalization. PNG "alt=" Wkiom1d5hmbsgxduaaaylcgcnhk020.png "/>

1, static data internationalization


Steps to internationalize data at rest:

(1). Create a resource file that stores a string of text displayed by all countries

A) file:. Properties

b) Name: Basic Name _ language abbreviation _ country abbreviation. properties

For example: Msg_zh_cn.properties store all Chinese

Msg_en_us.properties Store all English

(2). Get in the program

ResourceBundle class, can read the internationalized resource file!

The locale class, which represents a region, is used to determine which internationalized resource to use.


1.1. Locale API

Static locale Getdefault () gets the default Locale object in the JVM

String Getcountry () gets the abbreviation of the country name

String Getdisplaycountry () Gets the name of the country

String GetLanguage () Gets the shorthand for the current language

String Getdisplaylanguage () Gets the full name of the language

Package com.rk.i18n.demo;import java.util.locale;public class demo01{public static  void main (String[] args) {//Localization object:locale//  The object that encapsulates the language, country information, provided by Java.util//locale locale  = Locale.CHINA;//Locale locale = Locale.US; Locale locale = locale.getdefault (); String country = locale.getcountry (); String displaycountry = locale.getdisplaycountry (); String language = locale.getlanguage (); String displaylanguage = locale.getdisplaylanguage (); SYSTEM.OUT.PRINTLN (country);          //cn        system.out.println (displaycountry),    //China         system.out.println (language);          //zh        system.out.println (displaylanguage);   //Chinese         }} 


1.2. ResourceBundle API

Static ResourceBundle Getbundle (String basename,locale Locale) gets the ResourceBundle instance

String getString (String key) Gets the value from the resource according to key



1.3. Example


(1) Building Properties Files: Msg_zh_cn.properties and Msg_en_us.properties

Msg_zh_cn.properties

uname=\u59d3\u540dpwd=\u5bc6\u7801

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/83/A3/wKioL1d5jefT6vNlAAALbK1OAno343.png "title=" Properties. PNG "alt=" Wkiol1d5jeft6vnlaaalbk1oano343.png "/>


Msg_en_us.properties

Uname=user Namepwd=password

(2) Code acquisition

Package Com.rk.i18n.demo;import Java.util.locale;import java.util.resourcebundle;//internationalization-static data public class demo02{  public static void Main (string[] args) {//Chinese language environment locale locale = locale.us;//Create Tool class object Resourcebundleresourcebundle bundle = Resourcebundle.getbundle ("com.rk.i18n.demo.msg", locale);//Gets the value in the configuration file based on key string uname = Bundle.getstring ("uname"); String pwd = bundle.getstring ("pwd");//Output System.out.println (uname); System.out.println (PWD);}}


1.4, about the ResourceBundle resource file properties

File naming: Basic name, language abbreviation

Resource bundles belong to families whose members share a common base name, but whose names also has additional component s that identify their locales.  For example, the base name of a family of resource bundles might is "myresources". The family can and provide as many locale-specific members as needed, for example a German one named "Myresources_de".


File name: Country abbreviation

If there is different resources for different countries, you can make specializations:for example, "Myresources_de_ch" C Ontains objects for the German language (DE) in Switzerland (CH). If you want to only modify some of the resources in the the specialization, you can do so.


File naming: The default resource Bundle

The family should has a default resource bundle which simply had the same name as its family-"myresources"-and would b E used as the bundle of last resort if a specific locale was not supported.


File content: The resource bundle belonging to the same family contains the same items content.

Each resource bundle in a family contains the same items, but the items has been translated for the locale represented by that resource bundle. For example, both "MyResources" and "Myresources_de" could have a String of that ' s used on a button for canceling operations. In ' MyResources ' The String may contain ' Cancel ' and in ' myresources_de ' it may contain ' abbrechen '.


Java code: Get Resource Bundle

When your program needs a Locale-specific object, it loads the ResourceBundle class using the Getbundle method:


ResourceBundle myresources = Resourcebundle.getbundle ("MyResources", Currentlocale);



2. Dynamic Data Internationalization

Dynamic internationalization mainly involves numbers, currencies, percentages and dates

For example:

English: 1987-09-19¥1000

English: sep/09 1987


package com.rk.i18n.demo;import java.text.dateformat;import java.text.numberformat;import  java.text.parseexception;import java.util.date;import java.util.locale;import org.junit.test; public class demo03{//  internationalization  -  Dynamic text  - 0.  Overview public void  TESTI18N () {//  International Currency numberformat.getcurrencyinstance ();//  internationalization digital numberformat.getnumberinstance ();//   Internationalization percentage numberformat.getpercentinstance ();//  internationalization date// dateformat.getdatetimeinstance (DateStyle,  timestyle, alocale)}//  internationalization  -  Dynamic text  - 1.  International currency @testpublic void  testi18ncurrency () {//  Simulation language environment locale locale = locale.china;//  data preparation double  number = 100;//  Tool class Numberformat nf = numberformat.getcurrencyinstance (locale);//   International Currency String str = nf.format (number);//  output System.out.println (str);} Interview question:   code calculation:   $100 *&NBsp;10   @Testpublic  void testcurrency ()  throws parseexception{string str  =  "$;int num = 10;// 1. " analysis of which country's currency is the str value locale locale =  locale.us;// 2.  Internationalization Tool class numberformat nf = numberformat.getcurrencyinstance (locale);//  3.  parsing strnumber number = nf.parse (str);//4. Calculation int value =  Number.intvalue ()  * num;//5. Formatted output str = nf.format (value); System.out.println (str);}   Internationalization  -  Dynamic text  - 2.  internationalization value @testpublic void testi18nnumber () {locale  locale = locale.china; Numberformat nf = numberformat.getnumberinstance (locale); String str = nf.format (1000000000); System.out.println (str);}   Internationalization  -  dynamic text  - 3.  internationalization percent @testpublic void testi18npercent () {Locale  locale = Locale.CHINA; Numberformat nf = numberformaT.getpercentinstance (locale); String str = nf.format (0.325); System.out.println (str);}   Internationalization  -  Dynamic text  - 4.  internationalization date/* *  Date  *   FULL    2015 March 4   Wednesday  *   long   2015 March 4  *    full   2015 March 4   Wednesday  *    MEDIUM 2015-3-4 *     SHORT  15-3-4 *     *  Time  *    FULL    04:31 P.M. 59 seconds  CST *   LONG    04:32 P.M. 37 seconds  *    MEDIUM 16:33:00 *    SHORT   4:33  *     *  */@Testpublic  void testi18ndate () {int  datestyle = dateformat.full;int timestyle = dateformat.full; locale locale = locale.china;dateformat df = Dateformat.getdatetimeinstance (Datestyle, timestyle, locale); String date = df.format (New date ()); SYSTEM.OUT.PRINTLN (date);}   Interview 2:  Please  cst the time value:09-11-28  10:25 A.M. 39 seconds, and parse the inverse into a Date object. @Testpublic  void testdate ()  throws ParseException{String str =  "09-11-28   10:25 A.M. 39 sec  cst ";int datestyle = dateformat.short;int timestyle =  Dateformat.full; locale locale = locale.china;//  Create DateFormat Tool class, internationalized date dateformat df =  Dateformat.getdatetimeinstance (Datestyle, timestyle, locale);D ate date = df.parse (str ); SYSTEM.OUT.PRINTLN (date);}}




3. JSP page Internationalization


Data such as values, currencies, time, dates, and so on, can be generated dynamically when the program is running, so it is not possible to separate them from the application as simple as text, but to require special handling. The API classes that address these issues are available in Java (in the Java.util package and the Java.text package)


3.1. Preparation: Building Properties Resources

Create 2 Properties files under Com.rk.i18n.resource: Message_en_us.properties and Message_zh_cn.properties.


Message_zh_cn.properties

Title=\u4f60\u597d\uff0c\u8bf7\u767b\u5f55uname=\u7528\u6237\u540dpwd=\u5bc6\u7801submit=\u63d0\u4ea4

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/83/A4/wKiom1d5j8aArKdIAAAOCpAj0R8612.png "title=" Properties2. PNG "alt=" Wkiom1d5j8aarkdiaaaocpaj0r8612.png "/>

Message_en_us.properties

Title=plean Log Inuname=user namepwd=passwordsubmit=submit\!


3.2. Using JSP scripts for internationalization

<%@ page language= "java"  import= "java.util.*"  pageencoding= "UTF-8"%><! doctype html public  "-//w3c//dtd html 4.01 transitional//en" >


3.3. Use Jstl for internationalization


JSTL Tags:

Core Tag Library

internationalization and Formatting tag libraries

Database tag library (useless)

function library

<fmt:setlocale value= ""/> Set localization objects

<fmt:setbundle basename= ""/> Set Tool class

<fmt:message></fmt:message> Show internationalized text

Formatted value: <fmt:formatnumber pattern= "#.##" value= "100.99" ></fmt:formatNumber>

Formatted Date: <fmt:formatdate pattern= "Yyyy-mm-dd" value= "${date}"/>


One thing to note is that HttpServletRequest has a method of GetLocale () that can get the locale information in the current request, which can be used in an El expression ${pagecontext.request.locale} Get

<%@ page language= "java"  import= "java.util.*"  pageencoding= "UTF-8"%><%-- Introduction of Jstl internationalization and Formatting tag library  --%><% @taglib  uri= "http://java.sun.com/jsp/jstl/fmt"  prefix= "FMT"%> <! doctype html public  "-//w3c//dtd html 4.01 transitional//en" >


Formatting values and dates

<%@ page language= "java"  import= "java.util.*"  pageencoding= "UTF-8"%><% @taglib  uri= "http://java.sun.com/jsp/jstl/fmt"  prefix= "FMT"  %><! doctype html public  "-//w3c//dtd html 4.01 transitional//en" >


Javaweb Enhancement: Internationalization

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.