國際化動態文本(MessageFormat)

來源:互聯網
上載者:User

 

MessageFormat(動態文本)

如果一個字串中包含了多個與國際化相關的資料,可以使用MessageFormat類對這些資料進行批量處理。

例如:At 12:30 pm on jul 3,1998, a hurricance destroyed 99 houses and caused $1000000 of damage

以上字串中包含了時間、數字、貨幣等多個與國際化相關的資料,對於這種字串,可以使用MessageFormat類對其國際化相關的資料進行批量處理。

模式字串與預留位置

模式字串:

      At {0} on {1},a destroyed {2} houses and caused {3} of damage.

預留位置

l       MessageFormat類

•         MessageFormat(String pattern) 

•         執行個體化MessageFormat對象,並裝載相應的模式字串。

•         format(object obj[])

•         格式化輸出模式字串,參數數組中指定預留位置相應的替換對象。

•         format(new Object[ ]{date, new Integer(99), new Double(1E7) })

l       預留位置有三種方式書寫方式:

•         {argumentIndex}: 0-9 之間的數字,表示要格式化對象資料在參數數組中的索引號

•         {argumentIndex,formatType}: 參數的格式化類型

•         {argumentIndex,formatType,FormatStyle}: 格式化的樣式,它的值必須是與格式化類型相匹配的合法模式、或表示合法模式的字串。

 

Java中:8

//模式字串——含預留位置

       String pattern="At {0,time,full} on {0,date,long},a hurricance destroyed {1,number} houses and caused {2,number,currency} of damage.";

       MessageFormat mf=new MessageFormat(pattern,Locale.US);

       //構建對象數組,1e7——1乘以10的七次方

       Object []objs={new Date(),new Integer(99),new Double(1e7)};

       String result=mf.format(objs);

       System.out.println(result);

      

       //得到資來源物件

       ResourceBundle bundle=ResourceBundle.getBundle("com.hbsi.resource.MyResource", Locale.CHINA);

       result=bundle.getString("title");

       //System.out.println(result);

       MessageFormat mf1=new MessageFormat(result,Locale.CHINA);

      

       System.out.println(mf1.format(objs));

JSP中

<jsp:useBean id="date" class="java.util.Date"></jsp:useBean>

 <%

    request.setAttribute("number1",new Integer(99));

    request.setAttribute("number2",new Double(1e7));

   

  %>

    <fmt:setBundle basename="com.hbsi.resource.MyResource" var="bundle" scope="request"/>

    <fmt:message key="username" bundle="${bundle}"/><br>

    <fmt:message key="title" bundle="${bundle}">

    <fmt:param value="${date}"></fmt:param>

    <fmt:param value="${number1}"></fmt:param>

    <fmt:param value="${number2}"></fmt:param>

    </fmt:message><br>

    <fmt:message bundle="${bundle}">

    title

    <fmt:param value="${date}"></fmt:param>

    <fmt:param value="${number1}"></fmt:param>

    <fmt:param value="${number2}"></fmt:param>

</fmt:message>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.