JavaServer Faces (JSF) - JSF Convertor Tags - JSF Custom Converter - JavaServer Faces (JSF)

Define JSF Custom Convertor

Custom convertor in JSF can be created as desired.

A custom converter in JSF is defined in a three-step process.

Step
Description
1
Create a converter class by implementingjavax.faces.convert.Converterinterface.
2
Implement getAsObject() and getAsString() methods of above interface.
3
Use Annotation @FacesConvertor to assign a unique id to the custom convertor.

Step 1: Create a Converter Class: UrlConverter.java

Step 2: Implement Converter Interface Methods: UrlConverter.java

Create a simple class to store data: UrlData. This class will store a URL string.

Use UrlData in getAsObject method.

Step 3: Annotate to Register the Convertor : UrlConverter.java

Use the Convertor in JSF Page

Example Application

A test JSF application is created to test the above tag.

Step
Description
1
Create a project with a namehelloworldunder a packagecom.wisdomjobs.testas explained in theJSF - First Applicationchapter.
2
CreateUrlData.javaunder packagecom.wisdomjobs.testas explained below.
3
CreateUrlConvertor.javaas a converter under packagecom.wisdomjobs.testas explained below.
4
CreateUserData.javaas a managed bean under packagecom.wisdomjobs.testas explained below.
5
Modifyhome.xhtmlas explained below. Keep rest of the files unchanged.
6
Createresult.xhtmlin the webapps directory as explained below.
7
Compile and run the application to make sure the business logic is working as per the requirements.
8
Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver.
9
Launch your web application using appropriate URL as explained below in the last step.

UrlData.java

UrlConvertor.java

UserData.java

home.xhtml

result.xhtml

Once all the changes are done, the application is compiled and run as in JSF – Create Application chapter. On successful creation of the application, the result appears as:

JSF Custom Converter

If any invalid value is entered, then the error message appears as:

JSF Custom Converter Error Message

If valid value is entered, then the message appears as:

JSF Custom Converter Result

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JavaServer Faces (JSF) Topics