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>