爪哇一角

共同探讨STRUTS#HIBERNATE#SPRING#EJB等技术
posts - 3, comments - 6, trackbacks - 0, articles - 99
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

四 JSF转换器

Posted on 2009-01-20 14:47 非洲小白脸 阅读(369) 评论(0)  编辑  收藏 所属分类: JSF

1.JSF转换器的应用

Web应用程式与浏览器之间传送的资料基本上都是字串文字,而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里的信息的时候,如果Bean里的字段不是String类型的,则需要将其先转换成String类型。

例:

先定义一个Bean,里面包含了一个Date类型的变量。

package test;

import java.util.Date;

//JSF的转换器示例

public class JsfCoverter {

       private Date date = new Date();

    public Date getDate() {

        return date;

    }

    public void setDate(Date date) {

        this.date = date;

    }

}

 

再建立一个Jsp,用来显示JsfCoverter里面的变量date

<%@ 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="#{jsfcover.date}">

              <f:convertDateTime pattern="dd/MM/yyyy" />

       </h:outputText> </b>

       <h:form>

              <h:inputText id="dateField" value="#{jsfcover.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:inputText>中输入的是String类型的信息,但是和这个字段绑定的是一个Date变量(jsfcover.date),

因此你必须将输入的String类型转换成Date类型才行。而<f:convertDateTime>就是帮我们做这件事的。

如果转换出错的话,<h:message>则会显示错误信息。

 

当然,我们还需要配置定义的Bean,以及设子页面的跳转,才能正常运行。

<navigation-rule>

    <from-view-id>/*</from-view-id>

    <navigation-case>

        <from-outcome>show</from-outcome>

        <to-view-id>/pages/jsfCoverter.jsp</to-view-id>

    </navigation-case>

</navigation-rule>

 

<!-- jsf转换器 -->

<managed-bean>

    <managed-bean-name>jsfcover</managed-bean-name>

     <managed-bean-class>test.JsfCoverter</managed-bean-class>

    <managed-bean-scope>session</managed-bean-scope>

</managed-bean>

 

启动Tomcat,就可以运行了http://localhost:8080/jsfTest/pages/jsfCoverter.faces

具体程序参看示例程序.

 

2.自定义JSF转换器

除了使用标准的转换器之外,您还可以自行定制您的转换器,您可以实作javax.faces.convert.Converter接口,这个接口有两个要实作的方法:

public Object getAsObject(FacesContext context,

                           UIComponent component,

                           String str);

 public String getAsString(FacesContext context,

                           UIComponent component,

                           Object obj);

简单的说,第一个方法会接收从客户端经由HTTP传来的字符串数据,您在第一个方法中将之转换为您的自订对象,这个自订对象将会自动设定给您指定的Bean对象;

第二个方法就是将从您的Bean对象得到的对象转换为字符串,如此才能藉由HTTP传回给客户端。

 

上面的<f:convertDateTime>转换器可以将用户输入的String类型的信息转换成Beandate变量,显示时再由Date型转成String显示在页面上。

但是很多项目需要将用户输入的或者检索的不规则的Date格式统一化,这就需要用户自己定义一个共通的转换器了。

 

首先建立一个转换器,它要实现javax.faces.convert.Converter接口

package test;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.faces.application.FacesMessage;

import javax.faces.component.UIComponent;

import javax.faces.context.FacesContext;

import javax.faces.convert.Converter;

import javax.faces.convert.ConverterException;

public class JsfMyCoverter implements Converter {

       public Object getAsObject(FacesContext context, UIComponent component,

页面输入信息的转换

 
                     String obj) {

              // TODO Auto-generated method stub

              try {

                     Date date = new Date();

                     String objFor = obj.substring(0,4) + "-"

                            + obj.substring(4,6) + "-"

                            + obj.substring(6,8);

                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                     date = sdf.parse(objFor);

                     return date;

              } catch (Exception e) {

                     FacesMessage facesMessage = new FacesMessage(

                                   FacesMessage.SEVERITY_ERROR, "日期格式错误", "日期格式错误");

                     throw new ConverterException(facesMessage);

页面显示信息的转换

 
              }

       }

       public String getAsString(FacesContext context, UIComponent component,

                     Object obj) {

              // TODO Auto-generated method stub

              String res = null;

              if (obj instanceof Date) {

                     String pattern = "yyyy-MM-dd";

                     SimpleDateFormat sdf = new SimpleDateFormat(pattern);

                     res = sdf.format(obj);

                     return res;

              }

              return res;

       }

}

 

同时定义表示页面jsfMyCoverter.jsp.

别忘记faces-config.xml中完成注册:

<!-- 自定义转换器 -->

    <navigation-rule>

        <from-view-id>/*</from-view-id>

        <navigation-case>

            <from-outcome>myConverter</from-outcome>

            <to-view-id>/pages/jsfMyCoverter.jsp</to-view-id>

        </navigation-case>

    </navigation-rule>

 

<!-- 自定义转换器 -->

    <converter>

        <converter-id>dateFormatCoverter</converter-id>

        <converter-class>

            test.jsfMyCoverter

        </converter-class>

    </converter>

更新Tomcathttp://localhost:8080/jsfTest/pages/jsfMyCoverter.faces就可以看到自定义的转换器了。

具体程序参看示例程序。

 


只有注册用户登录后才能发表评论。


网站导航: