JSF---->标准转换器(Converter)

来源:互联网 发布:常见网络接口 编辑:程序博客网 时间:2024/05/25 18:12

转换器(Converter)协助模型与视图之间的数据转换


标准转换器

 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

package wsz.ncepu; 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

<%@ 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=utf-8"%> <f:view><html> <head> <title>转换器示范</title> </head> <body> 设定的日期是:           <b>           <h:outputText value="#{user.date}">               <f:convertDateTime pattern="yyyy/MM/dd"/>           </h:outputText>           </b>    <h:form>        <h:inputText id="dateField" value="#{user.date}">            <f:convertDateTime pattern="yyyy/MM/dd"/>        </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' encoding='UTF-8'?><faces-config xmlns="http://java.sun.com/xml/ns/javaee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"    version="1.2">     <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>            wsz.ncepu.UserBean        </managed-bean-class>        <managed-bean-scope>session</managed-bean-scope>    </managed-bean> </faces-config>

首次连上页面时显示的画面如下:

如您所看到的,转换器自动依pattern设定的样式将Date对象格式化了,当您依格式输入数据并送出后,转换器也会自动将您输入的数据转换为Date对象,如果转换时发生错误,则会出现以下的讯息:

 Using the Standard Converters 这篇文章中有关于标准转换器的说明。

 http://oss.org.cn/ossdocs/java/ee/javaeetutorial5/doc/JSFPage7.html