标准转换器

 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:

  • UserBean.java
UserBean.java
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的标准转换器来协助这项工作,例如:

  • index.jsp
index.jsp
<%@ 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是这样定义的:

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 这篇文章中有关于标准转换器的说明。