天天看點

javaee學習之路(十)國際化

例1、Locale類的用法

package cn.itcast.test;
import java.util.Locale;
public class TestLocale {
    public static void main(String[] args) {
        Locale locale=Locale.CHINA;
        System.out.println(locale.getCountry());//CN  國家代碼
        System.out.println(locale.getLanguage());//zh  語言代碼
        //獲得此java虛拟機執行個體的目前預設語言環境值
        locale = Locale.getDefault();
        System.out.println(locale);//zh_CN
        System.out.println("************************************");
        locale=Locale.US;
        System.out.println(locale.getCountry());//US 國家代碼
        System.out.println(locale.getLanguage());//en  語言代碼
    }
}
           

例2、DateFormat類的用法舉例。

package cn.itcast.test;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
public class TestDateFormat {
    public static void main(String[] args) throws ParseException {
        Locale locale=Locale.CHINA;
        Date date = new Date();
        DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT, locale);
        //講一個Date格式化為日期/時間字元串
        String source=df.format(date);
        System.out.println(source);//12-10-26

        df=DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
        source=df.format(date);
        System.out.println(source);//2012-10-26

        df=DateFormat.getDateInstance(DateFormat.LONG, locale);
        source=df.format(date);
        System.out.println(source);//2012年10月26日
        System.out.println("***********************************************");
        locale=Locale.US;
        date = new Date();
        df=DateFormat.getDateInstance(DateFormat.SHORT, locale);
        //講一個Date格式化為日期/時間字元串
        source=df.format(date);
        System.out.println(source);//10/26/12

        df=DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
        source=df.format(date);
        System.out.println(source);//Oct 26, 2012

        df=DateFormat.getDateInstance(DateFormat.LONG, locale);
        source=df.format(date);
        System.out.println(source);//October 26, 2012
        System.out.println("***********************************************");
        //從給定字元串的開始位置解析文本,以生成一個日期
        locale=Locale.CHINA;
        df=DateFormat.getDateInstance(DateFormat.LONG, locale);
        source="2012年10月26日";//上面應該設定為長格式

        System.out.println(df.parse(source).toString());
    }
}
           

例3、NumberFormat的用法。

package cn.itcast.test;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class TestNumberFormat {
    public static void main(String[] args) throws ParseException {
        Locale locale=Locale.CHINA;
        NumberFormat nf=NumberFormat.getInstance(locale);
        double number=;
        //格式規範
        String source = nf.format(number);
        System.out.println(source);//1,223,456,789.34
        System.out.println("***************************************");

        nf=NumberFormat.getInstance(Locale.FRANCE);
        source = nf.format(number);
        System.out.println(source);//1?223?456?789,34
        System.out.println("***************************************");
        source="1,223,456,789.34";
        nf=NumberFormat.getInstance(Locale.CHINA);
        System.out.println(nf.parse(source));
        System.out.println("***************************************");

    }
}
           

例4、MessageFormat案例介紹。

package cn.itcast.test;
import java.text.MessageFormat;
public class TestMessageFormat {
    public static void main(String[] args) {
        //pattern="I worked at itcast and good!"
        String pattern="I {0} at {1} and {2}!";
        MessageFormat mf=new MessageFormat(pattern);
        //格式化一個對象數組,并将messageFormat的模式添加到所提供的StringBuffer
        Object[] param=new Object[]{"worked","itcast","good"};
        StringBuffer sb=new StringBuffer();
        mf.format(param, sb, null);
        System.out.println(sb.toString());//I worked at itcast and good!
     /*
      * 如果  String pattern="I {1} at {0} and {2}!";
      * 則輸出為:I itcast at worked and good!
      */
    }
}
           

例5、資源包應用之ResourceBundle。

第一步、建立三個資源包(注意檔案名即路徑)

javaee學習之路(十)國際化

1. resource_zh_CN.properties

username=username_zhongwen
password=password_zhongwen
submit=login_zhongwen
           
  1. resource_en_US.properties
username=username_en
password=password_en
submit=login_en
           

第二步、

package cn.itcast.test;
import java.util.Locale;
import java.util.ResourceBundle;
public class TestResourceBundle {
    public static void main(String[] args) {
        Locale locale=Locale.CHINA;
        String baseName = "resource";
        readResource(baseName, locale);//username_zhongwen:password_zhongwen:login_zhongwen
/*****************************************************************************
        Locale locale=Locale.US;
        String baseName="resource";
        ResourceBundle rb=ResourceBundle.getBundle(baseName, locale);   
        String username = rb.getString("username");
        String password = rb.getString("password");
        String submit=rb.getString("submit");
        System.out.println(username+":"+password+":"+submit);
        //username_en:password_en:login_en
******************************************************************************/
    }
    public static void readResource(String baseName,Locale locale){
        ResourceBundle rb=ResourceBundle.getBundle(baseName, locale);   
        String username = rb.getString("username");
        String password = rb.getString("password");
        String submit=rb.getString("submit");
        System.out.println(username+":"+password+":"+submit);
    }
}
           

第三步、如果resource_zh_CN.properties改為一下内容,應當如何處理才能不産生亂碼問題呢?

username=使用者名
password=密碼
submit=登陸
           
  1. 建立一個resource_zh_CN.txt檔案(在Src目錄下面)
  2. 找到環境變量path中對應的目錄,裡面有個native2ascii.exe檔案,進行字元編碼

    具體方法:在DOS中執行以下内容:

    native2ascii –encoding gb2312 resource_zh_CN.txt resource_zh_CN.properties

    同時删除原來的resource_zh_CN.properties檔案,然後輕按兩下run.bat 即可将中文轉為ASCII

    javaee學習之路(十)國際化
    轉碼後的resource_zh_CN.properties為:
username=\u7528\u6237\u540d
password=\u5bc6\u7801
submit=\u767b\u9646
           

然後執行TestResourceBundle.java便可以得到如下内容:

使用者名:密碼:登陸

總結:

國際化原理:

1. 針對不同國家定義不同的資源檔案 基名是(resource)

資源檔案的字尾名是properties 檔案中儲存檔案的方式是key = value

在各個資源檔案中key值相同的,而value是不同的

1.1 中國 定義的資源檔案名稱是:resource_zh_CN.properties

username=\u7528\u6237\u540D
password=\u5BC6\u7801
submit=\u767B\u9646
           

美國 定義的資源檔案名稱是:resource_zh_CN.properties

username=username_en
password=password_en
submit=login_en
           

預設的資源檔案 resource.properties

*當要查找的資源檔案不存在時,讀取的該資源檔案

2.讀取資源檔案:

使用ResourceBundle.getBundle(baseName,locale);方法,它會根據基名和區域名稱自動查找對應的資源檔案:

基名:baseName=resource

區域:locale=Locale.CHINA;

3. 中文要進行字元編碼

3.1 定義jdk的環境變量

3.2 随便定義一個儲存中文資訊的檔案(.txt),使用批處理檔案進行檔案的轉碼:

例6、登陸頁面的國際化

javaee學習之路(十)國際化

.properties檔案與例5相同。

第一步、login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@page import="java.text.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
……
  <% 
      //擷取伺服器首選區域 
      Locale locale = request.getLocale(); 
      System.out.println("locale:"+locale);//locale:zh_CN  在IE中改了語言之後:locale:en_US 
      //擷取浏覽器中選擇的所有語言 
      Enumeration e=request.getLocales(); 
      while(e.hasMoreElements()){ 
          System.out.println("    "+e.nextElement());//zh_CN  en_US 
      } 
      //處理系統的時間 
      DateFormat df=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM,locale);
      String dateStr=df.format(new Date());
      //國際化
      ResourceBundle rb=ResourceBundle.getBundle("resource",locale);
   %>
    時間是:<%=dateStr %><br/>
    <form action="" method="post">
    <table border="1">
         <tr>
             <td style="text-align: right"><%=rb.getString("username") %>:</td>
             <td><input type="text" name="username"/></td>
         </tr>
         <tr>
             <td style="text-align: right"><%=rb.getString("password") %></td>
             <td><input type="password" name="password"/></td>
         </tr>
          <tr>
             <td style="text-align: right"><input type="submit" value="<%=rb.getString("submit") %>"/></td>
             <td><input type="reset" value="重置"/></td>
……
           

第二步、驗證,在IE中鍵入:http://localhost:8080/day19_i18nWeb/login.jsp

然後選擇浏覽器的工具–>正常->語言

javaee學習之路(十)國際化

然後上移相應内容,重新整理頁面可以看到頁面顯示不同内容!

例7、登陸頁面的國際化—使用标簽庫

第一步、将上面的第一步改為如下内容:login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
……
  <%
     Date date=new Date();
     pageContext.setAttribute("date",date);
   %>
  時間是:<fmt:formatDate value="${date}" dateStyle="MEDIUM" timeStyle="MEDIUM" type="both"/>
 <fmt:bundle basename="resource">
<!—-上面這行的标簽對等同于<fmt:setBundle basename="resource"/> -- >
    <form action="" method="post">
    <table border="1">
         <tr>
             <td style="text-align: right"><fmt:message key="username"/>:</td>
             <td><input type="text" name="username"/></td>
         </tr>
         <tr>
             <td style="text-align: right"><fmt:message key="password"/>:</td>
             <td><input type="password" name="password"/></td>
         </tr>
          <tr>
             <td style="text-align: right"><fmt:message key="submit"/>:</td>
             <td><input type="reset" value="重置"/></td>
         </tr>
    </table>
    </form>
    </fmt:bundle>
  </body>
</html>
           

第二步、驗證

例8、登陸頁面的國際化—使用标簽庫實作中英文切換

将例7中第一步改為如下内容:login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@page import="java.text.*" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
……
  <% 
  //定義locale的預設值 
     Locale l=Locale.CHINA; 
     String slocale = request.getParameter("locale"); 
     if(slocale!=null){ 
        if("zh".equals(slocale.trim())){ 
            l=Locale.CHINA; 
        } 
        if("en".equals(slocale.trim())){ 
            l=Locale.US;        
        } 
     } 
     pageContext.setAttribute("l",l); 
     Date date=new Date(); 
     pageContext.setAttribute("date",date); 
   %>
   <!-- 改變語言環境 -->
   <fmt:setLocale value="${l}"/>
  時間是:<fmt:formatDate value="${date}" dateStyle="MEDIUM" timeStyle="MEDIUM" type="both"/>
<fmt:setBundle basename="resource"/>
    <form action="" method="post">
    <table border="1">
         <tr>
             <td style="text-align: right"><fmt:message key="username"/>:</td>
             <td><input type="text" name="username"/></td>
         </tr>
         <tr>
             <td style="text-align: right"><fmt:message key="password"/>:</td>
             <td><input type="password" name="password"/></td>
         </tr>
          <tr>
             <td style="text-align: right"><fmt:message key="submit"/>:</td>
             <td><input type="reset" value="重置"/></td>
         </tr>
    </table>
    </form>
    <a href="${pageContext.request.contextPath}/loginch_en.jsp?locale=zh">中文</a>
    <a href="${pageContext.request.contextPath}/loginch_en.jsp?locale=en">English</a>
  </body>
</html>
           

第二步、驗證

javaee學習之路(十)國際化