Web應用程式與瀏覽器之間是使用HTTP進行溝通,所有傳送的資料基本上都是字串文字,而Java應用程式本身基本上則是物件,所以物件資料必須經由轉換傳送給瀏覽器,而瀏覽器送來的資料也必須轉換為物件才能使用。
JSF定義了一系列標準的轉換器(Converter),對於基本資料型態(primitive
type)或是其Wrapper類別,JSF會使用javax.faces.Boolean、javax.faces.Byte、
javax.faces.Character、javax.faces.Double、javax.faces.Float、
javax.faces.Integer、javax.faces.Long、javax.faces.Short等自動進行轉換,對於
BigDecimal、BigInteger,則會使用javax.faces.BigDecimal、javax.faces.BigInteger自
動進行轉換。
至於DateTime、Number,我們可以使用<f:convertDateTime>、<f: convertNumber>標籤進行轉換,它們各自提供有一些簡單的屬性,可以讓我們在轉換時指定一些轉換的格式細節。
來看個簡單的例子,首先我們定義一個簡單的Bean:
package onlyfun.caterpillar;
import java.util.Date;
public class UserBean { private Date date = new Date(); public Date getDate() { return date; }
public void setDate(Date date) { this.date = date; } }
這個Bean的屬性接受Date型態的參數,按理來說,接收到HTTP傳來的資料中若有相關的日期資訊,我們必須剖析這個資訊,再轉換為Date物件,然而我們可以使用JSF的標準轉換器來協助這項工作,例如:
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@page contentType="text/html;charset=Big5"%>
<f:view>
<html> <head> <title>轉換器示範</title> </head> <body>
設定的日期是: <b> <h:outputText value="#{user.date}"> <f:convertDateTime pattern="dd/MM/yyyy"/> </h:outputText> </b>
<h:form> <h:inputText id="dateField" value="#{user.date}"> <f:convertDateTime pattern="dd/MM/yyyy"/> </h:inputText> <h:message for="dateField" style="color:red"/> <br> <h:commandButton value="送出" action="show"/> </h:form> </body> </html> </f:view>
在<f:convertDateTime>中,我們使用pattern指定日期的樣式為dd/MM/yyyy,即「日/月/西元」格式,如果
轉換錯誤,則<h:message>可以顯示錯誤訊息,for屬性參考至<h:inputText>
的id屬性,表示將有關dateField的錯誤訊息顯示出來。
假設faces-config.xml是這樣定義的:
<?xml version="1.0"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config> <navigation-rule> <from-view-id>/*</from-view-id> <navigation-case> <from-outcome>show</from-outcome> <to-view-id>/pages/index.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class> onlyfun.caterpillar.UserBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> </faces-config>
首次連上頁面時顯示的畫面如下:

如您所看到的,轉換器自動依pattern設定的樣式將Date物件格式化了,當您依格式輸入資料並送出後,轉換器也會自動將您輸入的資料轉換為Date 物件,如果轉換時發生錯誤,則會出現以下的訊息:

<f:convertDateTime>標籤還有幾個可用的屬性,您可以參考 Tag Library Documentation 的說明,而依照類似的方式,您也可以使用<f:convertNumber>來轉換數值。
您還可以參考 Using the Standard Converters 這篇文章中有關於標準轉換器的說明。
|