`
zcdxzsz
  • 浏览: 74446 次
  • 来自: ...
社区版块
存档分类
最新评论

[转]Developing Custom Converters

    博客分类:
  • java
阅读更多
4.1) Introduction

In most of the situations, the Converter Implementations that are bundled with JSF implementation is often enough. However, for application specific purposes, there may be a need to customize and convert the user entered string into some other data-type. This can be achieved with ease by using JSF Pluggable Converter architecture.
4.2) Phone Number

Let us assume that our Web Application prompts the user to enter phone number which is of the format 'CountryCode-AreaCode-Number'. Note that whatever user enters is just a string and we want this string to be converted into some kind of format so that it can be stored in the model.

PhoneNumber.java


package net.javabeat.articles.jsf.converters;

import java.io.Serializable;

public class PhoneNumber implements Serializable
{
    private int countryCode;
    private int areaCode;
    private long number;        

    public PhoneNumber()
    {    
    }

    public PhoneNumber(int countryCode, int areaCode, long number) 
    {
        this.setCountryCode(countryCode);
        this.setAreaCode(areaCode);
        this.setNumber(number);                
    }

    public int getCountryCode() 
    {
        return countryCode;
    }

    public void setCountryCode(int countryCode) 
    {
        this.countryCode = countryCode;
    }

    public int getAreaCode()
    {
        return areaCode;
    }

    public void setAreaCode(int areaCode) 
    {
        this.areaCode = areaCode;
    }

    public long getNumber() 
    {
        return number;
    }

    public void setNumber(long number) 
    {
        this.number = number;
    }
}


The above model class for Phone Number encapsulates 'countryCode', 'areaCode' and 'number' properties. The rest of the code merely contains setters and getters for setting and getting the appropriate values.
4.3) Phone Number Converter

All the Converter classes in JSF must implement the Converter interface and they should override the getAsObject() and getAsString() methods. The method getAsObject() will be called as soon as the user enters the data and conforms it by clicking the submit button. This triggers the Apply Request Values Phase and this method will be called with the user-entered value as one of its arguments. Here we can parse and format the data entered by the user and store it in some model object and return it so that it will be set to the appropriate UI Component.

The getAsString() method will be called during Render Response Phase. Now, it's time to display the data in the view from the model object. And usually this method will contain logic for extracting the data from the model, format it and return it to the view.

PhoneNumberConverter.java


package net.javabeat.articles.jsf.converters;

import java.util.StringTokenizer;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

public class PhoneNumberConverter implements Converter 
{

    public PhoneNumberConverter() 
    {
    }

    public Object getAsObject(FacesContext context, UIComponent component, String value)
    {

        if (value == null || (value.trim().length() == 0))
        {
            return value;
        }

        PhoneNumber phoneNumber = new PhoneNumber();
        boolean conversionError = false;

        int hyphenCount = 0;
        StringTokenizer hyphenTokenizer = new StringTokenizer(value, "-");
        while (hyphenTokenizer.hasMoreTokens())
        {
            String token = hyphenTokenizer.nextToken();
            try
            {
                if (hyphenCount == 0)
                {   
                    phoneNumber.setCountryCode(Integer.parseInt(token));
                }

                if (hyphenCount == 1)
                {
                    phoneNumber.setAreaCode(Integer.parseInt(token));
                }

                if (hyphenCount == 2)
                {
                    phoneNumber.setNumber(Long.parseLong(token));
                }
                hyphenCount ++;       
            }
            catch (Exception exception)
            {
                conversionError = true;
            }
        }

        if (conversionError || (hyphenCount != 3))
        {
            throw new ConverterException();
        }

        return phoneNumber;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value)
    {
        PhoneNumber phoneNumber = null;

        if (value instanceof PhoneNumber)
        {
            phoneNumber = (PhoneNumber)value;

            StringBuilder phoneNumberAsString = new StringBuilder();
            phoneNumberAsString.append(phoneNumber.getCountryCode() + "-");
            phoneNumberAsString.append(phoneNumber.getAreaCode() + "-");
            phoneNumberAsString.append(phoneNumber.getNumber());
            return phoneNumberAsString.toString();
        }
        return "";
    } 
}


4.4) Registering the Custom Converter

To make the Custom Converter visible to JSF Application, we have to register the Converter class by making an entry in the Faces Configuration file. The following is the xml code snippet for the same,


<converter>
    <description>A Converter for phone number</description>
    <converter-id>PhoneNumberConverter</converter-id>
    <converter-class>
        net.javabeat.articles.jsf.converters.PhoneNumberConverter
    </converter-class>
</converter>


We have given an identifier 'PhoneNumberConverter' for the PhoneNumberConverter class and this identifier should be referenced elsewhere in the Application.
4.5) Using the Custom Converter

To set this Phone Number Converter to a component, make use of the 'converter' tag as the following listing does,


<h:inputText id="phoneNumberInput" 
value="#{phoneNumberBean.phoneNumber}" required="true">
    <f:converter converterId="PhoneNumberConverter"></f:converter>
</h:inputText>


分享到:
评论

相关推荐

    Google Blog Converters(博客数据转换)1.0

    【Google Blog Converters 1.0 - 博客数据转换详解】 在数字化时代,个人和企业经常使用博客作为在线表达观点、分享信息和构建社区的平台。随着时间的推移,可能会有更换博客服务提供商的需求,这时就需要将原有的...

    Converters

    "Converters"这一主题主要涉及的是文件转换工具,特别是与Microsoft Office相关的文件转换技术。在IT领域,文件转换器是一种软件应用,它允许用户将一个文件格式转换为另一种格式,以便于兼容不同的软件、操作系统...

    Power Electronics Converters, Applications, and Design

    ### Power Electronics Converters, Applications, and Design #### Power Electronic Systems 电力电子系统是现代工业、商业及日常生活中不可或缺的一部分。其基本功能在于控制并转换电能形式,使其满足特定负载...

    GRID CONVERTERS FOR PHOTOVOLTAIC AND WIND POWER SYSTEMS

    As a consequence, the grid converters should be able to exhibit advanced functions like: dynamic control of active and reactive current injection during faults, and grid services support.This book ...

    grails-plugin-converters-2.3.1.zip

    《Grails Plugin Converters 2.3.1与Box Java SDK v2:开源项目的融合与应用》 在当今数字化时代,开发高效的Web应用程序是至关重要的。Grails Plugin Converters 2.3.1 和 Box Java SDK v2 是两个在开源世界中备受...

    Understanding Delta-Sigma Data Converters电子书

    《理解Delta-Sigma数据转换器》是一本深入探讨Delta-Sigma(Σ-Δ)调制器技术的专业书籍,尤其适合那些希望深入理解这种高精度模拟数字转换器工作原理和设计方法的读者。Delta-Sigma调制器是现代信号处理领域中的...

    Voltage-Sourced Converters in Power Systems

    This is a much needed book recognizing that VSC technology is rapidly developing as it applies to electric power systems. It is so rapid that it is challenging to keep up with VSC confi gurations and ...

    CMOS Telecom Data Converters--2003 [609].pdf

    ### CMOS Telecom Data Converters #### 一、概述 《CMOS Telecom Data Converters》是一本专注于互补金属氧化物半导体(Complementary Metal-Oxide-Semiconductor,简称CMOS)技术在电信数据转换器中的应用的专业...

    C#简繁体转换工具包

    这个工具包基于微软提供的Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter类,它是一个高效且准确的转换库,广泛应用于多语言应用、网站和各种文本处理场景。 首先,让我们深入了解...

    Power electronics-converters applications and design

    电力电子学:转换器应用与设计 电力电子学是一门涉及电力转换、控制以及分配的学科,它在现代工业和日常生活中扮演着至关重要的角色。电力电子设备,尤其是转换器,是实现能源高效利用和环境可持续发展的重要工具。...

    Advanced_Data_Converters--[248].pdf

    《Advanced_Data_Converters--[248].pdf》是一本针对高性能数据转换器的综合指南,旨在帮助读者快速了解最新技术进展,并为特定应用选择最佳架构提供指导。 #### 二、主要内容概述 本书全面覆盖了高性能数据转换器...

    JESD204C-01 2022 SERIAL INTERFACE FOR DATA CONVERTERS.pdf

    "JESD204C-01 2022 SERIAL INTERFACE FOR DATA CONVERTERS.pdf" 本文将对JESD204C-01 2022 SERIAL INTERFACE FOR DATA CONVERTERS.pdf文件进行详细的知识点解析,该文件是JEDEC(Joint Electron Devices ...

    Understanding_Delta_Sigma_Data_Converters_Schreirer_Temes

    Delta-Sigma调制器的经典之作《Understanding Delta-Sigma Data Converters》由Richard Schreier和Gabor C. Temes编写。这本书由Analog Devices, Inc.的Richard Schreier与俄勒冈州立大学的Gabor C. Temes共同撰写,...

    SpringMVC源码总结(三)mvc:annotation-driven和mvc:message-converters简单介绍

    在Spring MVC框架中,`mvc:annotation-driven`和`mvc:message-converters`是两个非常重要的元素,它们在处理基于注解的控制器和数据转换方面起着关键作用。本篇文章将深入探讨这两个组件的工作原理以及如何在实际...

    small signal analysi sof parallel power converters

    small signal analysi sof parallel power converters

    Digital Control of High-Frequency Switched-Mode Power Converters

    《高频开关模式电源转换器的数字控制》是电力电子领域的一本重要著作,它深入探讨了在现代电力系统中如何高效、精确地管理和转换电能。该书由 Wiley-IEEE Press 出版于2015年,是研究和工程实践者的重要参考资料。...

Global site tag (gtag.js) - Google Analytics