JavaUsing Ajax with JSF in an Enterprise Application

Using Ajax with JSF in an Enterprise Application

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Using Ajax leverages efficiency in incorporating dynamic functionality of a web page. It has become more a necessity than luxury down through the years. Recall, when we enter keywords in Google search, a drop down list appears with a list of suggestions. They are loaded dynamically from the server end. What actually happens is, any text entered into the text box fires a request to the server which in turn loads some suggested keywords from the database and responds back in real time asynchronously without reloading the page. This is Ajax.

JSF and Ajax

In the Enterprise Java platform, Java Server Faces (JSF) provides built in support for Ajax. JSF pages can be in tune with Managed beans for validation and other purposes but Ajax when used appropriately within the JSF can leverage further and can go hand in hand boosting the performance and functionality of any mundane JSF page. Some commercial frameworks like IceFaces, Trinidad, J4Fry, PrimeFaces, provide a large set of Ajax enabled components with some enhanced specific behavior. Obviously, Managed bean is more than just performing validation; Ajax can be its suitable sidekick in an enterprise application, especially with respect to event-based-in-page rendering. Ajax comes in handy when it is to adding dynamic functionality in JSF with the advantage of less coding and more usage.

Traditional HTTP vs Ajax calls

In a traditional JSF, the browser makes an HTTP request to the server, and the server responses back with a JSF page (typically an XHTML page). For example, when a user clicks a button to submit a form, the browser makes a complete HTML document request and waits for the server to respond. The browser then loads the entire page and the user is taken to a whole new page.

HTTP Request and Response
HTTP Request and Response

Ajax, on the other hand makes a partial request from the server instead of full page reload. Only the Ajax enabled components in JSF gets updated while the user stays in the same page. What happens here is that the built in JavaScript library requests or sends data asynchronously and is responsible for updating only the Ajax enabled component. This obviously make JSF page rendering faster and more efficient.

XMLHTTP Request
XMLHTTP Request

With this added advantage there is certainly quite a bit of difference in how the call is made in Ajax enabled JSF. More than meets the eye, there is lot of Javascript functionality in Ajax. Here, JavaScript uses the Document Object Model (DOM) API such as XMLHttpRequest to exchange XML data from the browser to the server. Though transfer is done through XML, data can be realized in XHTML, JSON or in simple plain text format. As Ajax is natively supported in JSF 2.0, programmers can easily do without writing a single JavaScript code in a JSF page.

Use of Ajax in a JSF page

Ajax can be used to enhance JSF pages in various ways. One of the most common is validating forms in real-time without complete page reload. The following example demonstrates simple example in page validation check of a form.

Index.html

Field validation is one of the most common usages of Ajax. The name, userid and password components have validation that checks whether specified conditions are met before proceeding towards registration. Validation functions are written in backing bean (Registration.java). <f:ajax event=”blur”…> triggers an event as soon as the component loses focus and the validation function (e.g.<h:inputText… validator=”#{registration.validateName}) is called. If the function invalidates the data <h:message for=”name” id=”nameError” style=”color: red”/> is executed and the error message is displayed without the need of a whole page reload. This not only saves crucial time in an enterprise application but also the page itself becomes more user friendly.

<?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_h="http://xmlns.jcp.org/jsf/html"
      xmlns_f="http://xmlns.jcp.org/jsf/core">
<h:head>
      <title>JSF with AJAX</title>
</h:head>

<h:body>
 <h:form>
  <h3>Please enter the following information</h3>
      <table>
     <tr>
     <td>Name</td>
     <td>
      <h:inputText id="name" value="#{registration.name}" validator="#{registration.validateName}">
     <f:ajax event="blur" execute="@this" render="nameError"/>
     </h:inputText>
     </td>
     <td>
     <h:message for="name" id="nameError" style="color: red"/>
     </td>
     </tr>
     <tr>
     <td>User ID</td>
     <td>
     <h:inputText id="userid" value="#{registration.userId}" validator="#{registration.validateUserId}">
     <f:ajax event="blur" execute="@this" render="userIdError"/>
     </h:inputText>
     </td>
     <td>
     <h:message for="userid" id="userIdError" style="color: red"/>
     </td>
     </tr>
     <tr>
     <td>Password</td>
     <td>
     <h:inputSecret id="pass" value="#{registration.passwrod}" validator="#{registration.validatePassword}">
     <f:ajax event="blur" execute="@this" render="passError"/>    
     </h:inputSecret>
     </td>
     <td>
     <h:message for="pass" id="passError" style="color: red"/>
     </td>
     </tr>
     </table>
     <p><h:commandButton value="Register" action="welcome"/></p>           
     </h:form>
    </h:body>
</html>

Registration Form
Registration Form

Filled In Registration Form
Filled In Registration Form

welcome.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_h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Welcome</title>
    </h:head>
    <h:body>
    <h3>Welcome, #{registration.name}, you now registered user.</h3>
    </h:body>
</html>

Welcome
Welcome

Registration.java

package org.mano.ajaxdemo;
 
//...import statements
 
@Named(value = "registration")
@SessionScoped
public class Registration implements Serializable{
 
    private String name;
    private String userId;
    private String passwrod;
    
//...getters and setters
 
    public void validateName(FacesContext f, UIComponent c, Object obj){
        String s=(String)obj;
        if(s.length()==0)
            throw new ValidatorException(new FacesMessage("Name cannot be empty."));        
    }
    public void validateUserId(FacesContext f, UIComponent c, Object obj){
        String s=(String)obj;
        if(s.length()==0)
            throw new ValidatorException(new FacesMessage("UserID cannot be empty."));        
    }
    public void validatePassword(FacesContext f, UIComponent c, Object obj){
        String s=(String)obj;
        if(s.length()<8)
            throw new ValidatorException(new FacesMessage("Password must be >= 8 characters. "));        
    }
   
}
 

The validation function (e.g. validateName) takes three parameters:

  • javax.faces.context.FacesContext is an abstract class that represents contextual information associated with the processing of an incoming request and creates the response. This class is responsible for interaction with the JSF environment and its UI counterparts.
  • javax.faces.component.UIComponent is the base class for all UI components of JSF. This class can be used to directly access UI components from Java code.
  • Object holds the component value which in the above case is a String.

Once the function invalidates data a ValidatorException is thrown and a new FacesMessage is forwarded to the message component bound to the input component (e.g. <h:message for=”name” id=”nameError” style=”color: red”/>).

Conclusion

Though it’s not a comprehensive list of all the capabilities of Ajax in JSF but one can get an idea of its usage nonetheless. The biggest advantage of using Ajax in JSF is its in page rendering capability. Though there is no compulsion, enterprise application developers can use it to build an efficient web interface marrying Ajax capabilities and rich UI features of JSF and commercially available JSF enhanced frameworks such as – PrimeFaces, IceFaces, etc.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories