In-depth analysis of JavaWeb Item22 -- internationalization (i18n)

Source: Internet
Author: User
Tags i18n

In-depth analysis of JavaWeb Item22 -- internationalization (i18n)
I. Overview of international development

  Internationalization of software: When developing software, you must enable it to respond to accesses from different regions and countries in the world at the same time, provide pages or data that meet the reading habits of visitors.
  
Internationalization is also calledI18n(The reading method is I 18 n. It is said that the word internationalization (internationalization) has 18 English letters from I to n, and the i18n name comes from this)

Ii. qualified international software

Software Internationalization requires the following two features:
  
1,Fixed text elements used in the programSuch as text elements, error messages, and status information used in the menu bar and navigation bar,Select texts in different languages based on the visitor's region and country..
2,Dynamically generated program data, For example (date, currency, etc ),The software should be able to display according to the cultural habits of the current country or region.

Iii. Internationalization of fixed text elements

You can write fixed text information such as the menu bar, navigation bar, error message, and status information in the software in a properties file, compile different properties files according to different countries. This group of properties files is called a resource package.
  
The Java API providesResourceBundle classUsed to describe a resource package, and the ResourceBundle class provides the corresponding methodGetBundleThis method can be automatically displayed based on the visitor's country and region's corresponding resource file.

3.1 create Resource Packages and resource files

Each resource file in a resource package must have a commonBase name. In addition to the base name, each resource file name must contain an additional part that identifies its local information. For example, the base name of a resource package is"myproperties", The resource file name corresponding to the Chinese or English environment is:"myproperties_zh.properties""myproperties_en.properties"


  
Each resource package should have a default resource file, which does not contain additional parts that identify local information. If the ResourceBundle object cannot find the resource file that matches the user in the resource package, it selects the resource file that is closest to the user in the resource package. If the resource file cannot be found, the default resource file is used. For example:myproperties.properties

3.2. Resource file writing format

The content of resource files is usually used"Keyword = value"The software displays the keyword search value on the page. The keywords of all resource files in a resource package must be the same, and the value is the text of the corresponding country.
  
In addition, the resource file uses the properties format file,Therefore, all characters in the file must be ASCII characters. The properties file cannot store Chinese characters. Non-acsixes such as Chinese characters must be encoded first.

For example:

Properties file of International Chinese Environment

  

Properties file for International English environment

  

Java provides an native2ascII tool to encode Chinese characters. The usage of native2ascII is as follows:

  

3.3 programming to internationalize fixed text

A ResourceBundle class is provided in Java API to describe a resource package, and the ResourceBundle class provides the corresponding method getBundle, this method can be automatically displayed based on the corresponding resource file obtained by the visitor's country and region.

The ResourceBundle class provides a static method getBundle, which is used to load resource files and create a ResourceBundle instance:

 Locale currentLocale = Locale.getDefault(); ResourceBundle myResources =ResourceBundle.getBundle(basename, currentLocale);

Basename is the base name of the resource package (and must be the complete path ).
If the resource package subclass that matches the locale object cannot be found. Generally, the default resource file is used for display.
After the resource file is loaded, the program can callGetStringMethod to obtain the value corresponding to the specified Resource Information name.

 String value =  myResources.getString(“key");

Example: automatically obtain the corresponding resource file according to the country or region

Package me. gacl. i18n; import java. util. locale; import java. util. resourceBundle;/*** @ ClassName: I18NTest * @ Description: programming to internationalize fixed text * @ author: lone wolf * @ date: 9:34:05 **/public class I18NTest {public static void main (String [] args) {// Resource Package base name (package name + myproperties) String basename = "me. gacl. i18n. resource. myproperties "; // set the language environment Locale cn = Locale. CHINA; // Chinese Locale us = Locale. US; // english // based on the base name and Language Environment Loads the corresponding language resource file ResourceBundle myResourcesCN = ResourceBundle. getBundle (basename, cn); // load myproperties_zh.properties ResourceBundle myResourcesUS = ResourceBundle. getBundle (basename, us); // After the myproperties_en.properties is loaded, the program can call the getString method of the ResourceBundle instance object to obtain the value of the specified Resource Information name. // String value = myResources. getString ("key"); String usernameCN = myResourcesCN. getString ("username"); String passwordCN = myResourcesCN. getString ("password"); String usernameUS = myResourcesUS. getString ("username"); String passwordUS = myResourcesUS. getString ("password"); System. out. println (usernameCN + "--" + passwordCN); System. out. println (usernameUS + "--" + passwordUS );}}

Running result:

  

3.4. Internationalization of fixed text in WEB Applications

As follows:

<%@ page language="java"  import="java.util.*" pageEncoding="UTF-8"%>
<% // Load the i18n resource file, request. getLocale () gets ResourceBundle myResourcesBundle = ResourceBundle in the country where the access user is located. getBundle ("me. gacl. i18n. resource. myproperties ", request. getLocale (); %>

Running result:

The browser language is the display effect in the Chinese environment:

  

The browser language is the display effect in an English environment:

  

On the same page, different languages and texts are displayed in browsers in different language environments, so as to internationalize fixed texts.

Use languages in IE: Tools → Internet Options

  


 
 

Iv. Internationalization of Dynamic Data

Numeric value, currency, time, date, and other data may be dynamically generated when the program is running, so they cannot be separated from the application as simply as text, but need special processing. Java providesAPI class (In the java. util package and java. text package)

4.1. Locale class

Locale instance objects represent a specific geographic, political, and cultural region.
A Locale object does not verify that the information in the language and country is correct.Local sensitiveThe format and resolution tasks related to internationalization are completed by local sensitive classes. (If a class in JDK needs to adjust its function according to the Locale object during runtime, this class is calledLocal sensitive class)

4.2. DateFormat (date formatting)

The DateFormat class can format a date/time object as a date/time string that represents a country or region.
In addition to formatting the output date by country, the DateFormat class also defines int constants used to describe the display mode of date/time, including FULL, LONG, MEDIUM, DEFAULT, when instantiating a DateFormat object, you can use these constants to control the display length of the date/time.

4.2.1 instantiate the DateFormat class

There are nine ways to instantiate the DateFormat class. The following three methods are with parameters. The three methods listed below can also be without parameters or with only display style parameters.

getDateInstance(int style, Locale aLocale): Obtains the DateFormat instance object in the specified date display mode and local information. This instance object does not process the time value part. getTimeInstance(int style, Locale aLocale): Obtains the DateFormat instance object in the specified time display mode and local information. This instance object does not process the date value part. getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale): Obtain the DateFormat instance object by specifying the date display mode, time display mode, and local information.

4.2.2 method of DateFormat object    

Format: format the date object as a string that meets the requirements of a local environment.
Parse: parses a string into a date/time object.
Note: parse and format are the opposite. One is to convert the date time to the display style of the corresponding region and country, and the other is to convert the time and date of the corresponding region to the date object, when this method is used, the resolution time or date must comply with the specified country or region format. Otherwise, an exception is thrown.
  The DateFormat object is generally not thread-safe. Each thread should create its own DateFormat instance object.

4.2.3. Example of DateFormat

Package me. gacl. i18n; import java. text. dateFormat; import java. text. parseException; import java. util. date; import java. util. locale;/*** @ ClassName: DateFormatTest * @ Description: dateFormat test * DateFormat can format a date/time object as a date/time string * @ author: lone wolf * @ date: 10:03:26 **/public class DateFormatTest {public static void main (String [] args) throws ParseException {Date date Date = new Date (); // current moment time (date, time) // output date part DateFormat df = DateFormat. getDateInstance (DateFormat. FULL, Locale. GERMAN); String result = df. format (date); System. out. println (result); // output time df = DateFormat. getTimeInstance (DateFormat. FULL, Locale. CHINA); result = df. format (date); System. out. println (result); // output Date and Time df = DateFormat. getDateTimeInstance (DateFormat. SHORT, DateFormat. LONG, Locale. CHINA); result = df. format (date); System. out. println (result); // reverse parses the String into a date object String s = "10-9-26 02:49:53 P.M."; df = DateFormat. getDateTimeInstance (DateFormat. SHORT, DateFormat. LONG, Locale. CHINA); Date d = df. parse (s); System. out. println (d );}}
4.3. NumberFormat (number formatting)

The NumberFormat class can format a value into a numeric string that meets the habits of a country or region, or parse a numeric string that meets the habits of a country or region into a numeric value.
NumberFormat class method:
Format: format a value as a numeric string that meets the habits of a country or region.
Parse method: parses a numeric string that meets the habits of a country or region into a corresponding numeric string.
When instantiating the NumberFormat class, you can use the locale object as the parameter or do not use it. The following lists the parameters used.

getNumberInstance(Locale locale): Obtain the NumberFormat Instance Object for multiple purposes using the local information identified by the parameter locale object getIntegerInstance(Locale locale): Obtain the NumberFormat instance object that processes integers with the local information identified by the parameter locale object getCurrencyInstance(Locale locale): Obtain the NumberFormat Instance Object for processing currency with the local information identified by the parameter locale object getPercentInstance(Locale locale): Obtain the NumberFormat instance object that processes percentage values based on the local information identified by the locale object.
Example:
Package me. gacl. i18n; import java. text. numberFormat; import java. text. parseException; import java. util. locale;/*** @ ClassName: NumberFormatTest * @ Description: NumberFormat class test * @ author: lone wolf * @ date: 10:25:29 **/public class NumberFormatTest {public static void main (String [] args) throws ParseException {int price = 89; NumberFormat nf = NumberFormat. getCurrencyInstance (Locale. CHINA); String result = nf. format (price); System. out. println (result); String s = "¥89.00"; nf = NumberFormat. getCurrencyInstance (Locale. CHINA); Number n = nf. parse (s); System. out. println (n. doubleValue () + 1); double num = 0.5; nf = NumberFormat. getPercentInstance (); System. out. println (nf. format (num ));}}

Running result:

  

4.4. MessageFormat (Text Format)

If a string contains multiple data related to internationalization, you can use the MessageFormat class to batch process the data.
For example:At pm on jul 1000000, a hurricance destroyed 99 houses and caused $ of damage
The preceding strings contain time, number, currency, and other data related to internationalization. For such strings, you can use the MessageFormat class to batch process data related to internationalization.
  
How does the MessageFormat class Perform Batch Processing?
1. The MessageFormat class allows developers to replace sensitive data (international data) in strings with placeholders ).
2. When formatting and outputting text containing placeholders, The MessageFormat class can receive an array of parameters to replace each placeholder in the text.

4.4.1. Pattern strings and placeholders

Mode string:

At{0}On{1}, A destroyed{2}Houses and caused{3}Of damage

{0}, {1}, {2}, and {3} in the string are placeholders.

4.4.2 Format String

1. instantiate the MessageFormat object and load the corresponding mode string.

2. format (object obj []) is used to format the output mode string, and The placeholder replacement object is specified in the parameter array.

Example:

Package me. gacl. i18n; import java. text. messageFormat; import java. util. date; import java. util. locale;/*** @ ClassName: MessageFormatTest * @ Description: MessageFormat class test * @ author: lone wolf * @ date: 10:29:19 **/public class MessageFormatTest {public static void main (String [] args) {// mode String pattern = "On {0 }, a hurricance destroyed {1} houses and caused {2} of damage. "; // instantiate the MessageFormat object and load the corresponding mode string MessageFormat = new MessageFormat (pattern, Locale. CHINA); Object arr [] = {new Date (), 99,100 000000}; // formatted String, which specifies the placeholder replacement Object String result = format in the parameter array. format (arr); System. out. println (result );}}

Running result:

  

4.4.3. Three writing methods for placeholders

{ArgumentIndex}: number between 0 and 9, indicating the index number of the object data to be formatted in the parameter Array
{ArgumentIndex, formatType}: format type of the Parameter
{ArgumentIndex, formatType, FormatStyle}: formatted style. Its value must be a valid pattern that matches the formatting type or a string that represents a valid pattern.

Example:

Package me. gacl. i18n; import java. text. messageFormat; import java. util. date; import java. util. locale;/*** @ ClassName: MessageFormatTest * @ Description: MessageFormat class test * @ author: lone wolf * @ date: 10:29:19 **/public class MessageFormatTest {public static void main (String [] args) {// mode String pattern = "At {0, time, short} on {0, date}, a destroyed {1} houses and caused {2, number, currency} of damage. "; // instantiate the MessageFormat object and load the corresponding mode string MessageFormat = new MessageFormat (pattern, Locale. US); Object arr [] = {new Date (), 99,100 000000}; // formatted String, which specifies the placeholder replacement Object String result = format in the parameter array. format (arr); System. out. println (result );}}

Running result:

  

5. Using the international tag library in WEB applications to internationalize fixed text 5.1 International tags

Set a global region code
Set unified Request Encoding
Instance:

<%@ page language="java" contentType="text/html; charset=gb2312" import="java.util.*"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Chinese-Mainland:
English:

Page output:

Chinese-Mainland: English: Dec 16,201 5
5.2. Information Display tag

Set the resource file to be read temporarily
Get value through key
Sets a global resource file to be read.

Instance:

 <%@ page language="java" contentType="text/html; charset=gb2312" import="java.util.*"%><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Database driver name:
Connection string:
User name:
Password:
Name:
Dynamic prompt information:
Dynamic prompt information: Zhang San

The corresponding read file is dbconn. properties (of course, it is placed under web-inf/classes), and the content is:

# SQL ServerdriverName = com. microsoft. jdbc. sqlserver. SQLServerDriverconnString = jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = testDatabaseuserName = sa password = 123456 name = Xiao Pingguo messageTemp = myname is {0}, today is {1, date}

The page output is:

Database driver name: com. microsoft. jdbc. sqlserver. SQLServerDriver connection string: jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = testDatabase Username: sa password: 123456 name: Wallace dynamic prompt message: myname is {0 }, today is {1, date} dynamic prompt information: myname is xiaopingguo, today is

Several of the labels are described as follows:

Tags are used to bind the data source. properties file;


  
   
Statement, Code, etc.
  

A tag is used to extract the specified key value from the specified resource file;

If var is used, it will not be output directly on the page. Tag to output the page, as shown in the preceding example;

Tags can work Label to set The dynamic value of the tag pointing to the key, as shown in the preceding example;

Tags are used to set the default data source;


  
   
Tags are used to set the default data source;
   
  
5.3 format tags for numbers and dates

Format the date, and format the common date display as the standard date format.
The format of the formatted standard date is converted to a common type, such as a string
Formatting a number, formatting a common number into a standard number format
Deformat the number and convert the formatted number into a common number.
Set a Global Time Zone
Set a temporary Time Zone

Instance:

<%@ page contentType="text/html" pageEncoding="GBK"%><%@ page import="java.util.*"%><%@ taglib prefix="fmt" uri=“http://java.sun.com/jsp/jstl/fmt” %>
<% PageContext. setAttribute ("dateref", new Date (); %> Default display date and Time: $ {date} Custom format display date and Time: $ {date}

-Type: Specifies the format to be formatted. For example, only the date is formatted, only the time is formatted, or both are formatted. The default value is date. Generally, the format is both.
-Datestyle: Specifies the display style of the date. The default value is default.
-Timestyle: display style of the specified time. The default value is default.
-Pattern: the format to be specified when customizing the date display format, for example: MM minute ss second SSS Ms At HH on mm dd, yyyy (case-sensitive, in order not to be confused with the same letter)


  
   
Format the number: $ {num}
   
    
Scientific Notation: $ {num}
   
  

-- MaxIntegerDigits: The maximum integer that can be displayed.
-- MaxFractionDigits: Maximum number of decimal places that can be displayed
-- GroupingUsed: whether to add "," to the number

   
           
      
   
  

Finally, let's look at the following example:

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% -- import the international tag library -- %> <% @ taglib uri =" http://java.sun.com/jsp/jstl/fmt "prefix =" fmt "%>
<% -- // Load the i18n resource file, request. getLocale () gets ResourceBundle myResourcesBundle = ResourceBundle in the country where the access user is located. getBundle ("me. gacl. i18n. resource. myproperties ", request. getLocale (); -- %> <%--

The above is the summary of internationalization in Java Web development.

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.