Table of contents
1.
Introduction
2.
Custom Converter
3.
Custom Converter in JSF is defined in three steps:
4.
Creating a Custom Converter
5.
Example:
5.1.
UrlData.java
5.2.
UrlConverter.java
5.3.
UserData.java
5.4.
home.xhtml
5.5.
result.xhtml
6.
Frequently Asked Questions
6.1.
What does the JSF f:converter tag mean?
6.2.
What is the f:convertNumber tag in JSF?
6.3.
How does JSF relate to a bean method?
6.4.
Describe Facelets.
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

JSF Custom Converter

Author Ayush Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello, Ninja! Have you ever found a situation where you needed to convert a string into objects and an object into a string? You will run across issues while designing websites where conversion is necessary. JSF has a built-in tag for the string to objects and vice-versa.

You will discover JSF Custom Converter in this blog. Let's get going!

Custom Converter

A JavaServer Faces converter class transforms strings into objects and objects into strings. For this reason, JavaServer Faces offers several standard converters. 

As stated in Conversion Model, you can develop a custom converter to carry out this specific conversion if the regular converters available with JavaServer Faces cannot do so. The minimal need for this implementation is to specify how to convert data in both directions between the two perspectives of the data outlined in the Conversion Model.

The javax.faces.convert.Converter interface must be implemented by any custom converters. This section covers how to use this interface to carry out a unique data conversion.

Custom Converter in JSF is defined in three steps:

Step 1: Implement the javax.faces.convert.Converter interface to create a converter class.

Step 2: Implement the getAsString() and getAsObject() interface methods.

Step 3: To give the customized convertor a special id, use the annotation @FacesConvertor.

Creating a Custom Converter

Step 1: Create a Converter Class: UrlConverter.java

public class UrlConverter implements Converter {
...
}

 

Step 2: Use UrlConverter.java to implement the converter interface methods.

public class UrlData {
   private String url;
   
   public UrlData(String url) {
      this.url = url;
   }
   ...
}

public class UrlConverter implements Converter {
   
   @Override
   public Object getAsObject(FacesContext facesContext,
      UIComponent component, String value) {
      ...
      UrlData urlData = new UrlData(url.toString()); 
      return urlData;
   }

   @Override
   public String getAsString(FacesContext facesContext, 
      UIComponent component, Object value) {
      return value.toString();
   }
}

 

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

@FacesConverter("com.codingNinjas.test.UrlConverter")
public class UrlConverter implements Converter {
}

 

Step 4: Utilize the JSF Page Convertor.

<h:inputText id = "urlInput" value = "#{userData.data}" label = "URL" >
   <f:converter converterId = "com.codingNinjas.test.UrlConverter" />
</h:inputText>

Example:

Let's build a test JSF application to test the tag mentioned above.

Step 1: reate a project called helloworld under the package com.codingNinjas.test.

Step 2: Create UrlData.java under package com.codingNinjas.test as explained below.

Step 3: Add UrlConvertor.java as a converter to the com.codingNnijas.test package.

Step 4: Add UserData.java as a managed bean to the com.codingNinjas.test package.
Step 5: Make the changes outlined below to home.xhtml. Leave the remaining files alone.

Step 6: As stated below, create a result.xhtml in the webapps directory.

Step 7: To ensure that the business logic operates by the requirements, compile and execute the application.

Step 8: Create the programme as a war file, then deploy it to the Apache Tomcat Webserver.

Step 9: Launch your web application using the appropriate URL, as explained below in the last step.

UrlData.java

package com.codingNinjas.test;
public class UrlData {
   private String url;
   
   public UrlData(String url) {
      this.url = url;
   }
   
   public String getUrl() {
      return url;
   }

   public void setUrl(String url) {
      this.url = url;
   }
   
   public String toString() {
      return url;
   }
}

UrlConverter.java

package com.codingNinjas.test;
import java.net.URI;
import java.net.URISyntaxException;
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;
import javax.faces.convert.FacesConverter;
@FacesConverter("com.codingNinjas.test.UrlConverter")
public class UrlConverter implements Converter {

   @Override
   public Object getAsObject(FacesContext facesContext, 
      UIComponent component, String value) {
      StringBuilder url = new StringBuilder();

      if(!value.startsWith("http://", 0)) {
         url.append("http://");
      }
      url.append(value);


      try {
         new URI(url.toString());         
      } catch (URISyntaxException e) {
         FacesMessage msg = new FacesMessage("Error converting URL",
            "Invalid URL format");
         msg.setSeverity(FacesMessage.SEVERITY_ERROR);
         throw new ConverterException(msg);
      }

      UrlData urlData = new UrlData(url.toString()); 
      return urlData;
   }

   @Override
   public String getAsString(FacesContext facesContext,
      UIComponent component, Object value) {
         return value.toString();
   }
}

UserData.java

package com.codingNinjas.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {

   private static final long serialVersionUID = 1L;
   public UrlData data;

   public UrlData getData() {
      return data;
   }

   public void setData(UrlData data) {
      this.data = data;
   }

home.xhtml

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"   
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:f = "http://java.sun.com/jsf/core">
   <h:head>
      <title>JSF tutorial</title> 
   </h:head>
   
   <h:body>
      <h2>Custom Converter Example</h2>
      
      <h:form>
         <h:inputText id = "urlInput" value = "#{userData.data}" 
            label = "URL" >
            <f:converter converterId = "com.codingNinjas.test.UrlConverter" />
         </h:inputText>  
         <h:commandButton value = "submit" action = "result"/>
         <h:message for = "urlInput" style = "color:red" />
      </h:form>
   
   </h:body>
</html>

result.xhtml

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:f = "http://java.sun.com/jsf/core"    
   xmlns:h = "http://java.sun.com/jsf/html"
   xmlns:ui = "http://java.sun.com/jsf/facelets">
   
   <h:body>
      <h2>Result</h2>
      <hr />
      #{userData.data}   
   </h:body>
</html>

 

Let's build and execute the application after you finish all the modifications. This will result in the following outcome if everything with your application is in order.

Press the Submit button after entering an incorrect value. Observe the error notice below.

Press the Submit button after entering any legal value. View the outcome below.

Frequently Asked Questions

What does the JSF f:converter tag mean?

It is a tag for a core converter. It is used to extend the parent component with any converter.

What is the f:convertNumber tag in JSF?

It transforms user input data from components into a Java Number type. By nesting the convertNumber tag within the component tag, you may convert the data in an element to a java.lang.Number. Several characteristics are available for the convertNumber tag that let you choose the data type and format.

How does JSF relate to a bean method?

We refer to a managed bean method that performs navigation processing for the component and returns a logical outcome String.

Describe Facelets.

It is a lightweight page declaration language used to build JavaServer Faces views using HTML style.

Conclusion

Finally, you have reached the article's conclusion. Congratulations!! You gained knowledge of JSF's custom converter in this blog.

Are you eager to read more articles on JSF? Coding Ninjas cover you, so don't worry. View the JSF to learn more.

Please refer to our guided pathways on Code studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Please do upvote our blogs if you find them helpful and informative!

Happy learning!

Live masterclass