Primefaces AjaxBehavior and AjaxExceptionHandler Component Example Tutorial

Filed Under: JSF

Different tutorials were provided here have introduced various Primefaces components and the way in which Ajax component could be used for ajaxifying. Using of ajax component won’t be helpful if you don’t look at deeply. This tutorial aimed to help you gather the required information that makes the use of ajax component much easier.

Besides all of that important information that you will get here about ajax component, following also the life-cycle of the ajax request/response phases as it’s supported by the JSF 2 framework.

Ajax behavior was introduced firstly by the jsf 2 specification, and Primefaces is one of those libraries built on, so you will not find a big difference between standard jsf ajax component f:ajax and Primefaces ajax component p:ajax except the latter used with the Primefaces components.

This tutorial assumed that you’re using Eclipse IDE and Maven building tool for developing the suggested samples below. In case you’re never using it, it’s good for you looking into Primefaces beginners tutorial that help you doing that easily.

Ajax Lifecycle

Since JSF 2 release, ajax request/response becomes supported by the JSF lifecycle intuitively. No additional phases added for the original well-known JSF lifecycle, rather the same lifecycle has been evolved to serve the Asynchronous JavaScript And XML (Ajax) request/response mechanism. This tutorial isn’t intended for covering all details of ajax behavior that built-in originally. Keeping you aware of the original mechanism that was provided by the JSF implementation for ajaxify is the goal of this tutorial. More detailed information would be provided later in a specific JSF 2 tutorial.

The below figures depict you which phases are executed for handling the ajax request and which ones for a response.

AjaxBehavior - Request Phases

Request Phases

AjaxBehavior - Response Phases

Response Phases

JSF 2.0, splits the jsf lifecycle into two parts: execute (where components are executed) and render. Any given ajax request you can specify your executed components as well as those rendered.

Primefaces had compliant with these parts with minor changes here, instead of using execute and render attributes associated with f:ajax to indicate which components should be executed and rendered respectively, they become process and update attributes associated this time with p:ajax component.

The main goal of Ajax is to process the partial form rather than processing the whole form. Using ajax help you submitting those components mentioned in the process while the only components mentioned in the update are rendered and modified. At the other side, using a normal request/response, the whole form has been processed and updated per every request/response cycle which may cause a performance headache or end user uncomfortable issues.

AjaxBehavior Basic Info

Tag ajax
Behavior Id org.primfaces.component.AjaxBehavior
Behavior Class org.primefaces.component.behvior.ajax.AjaxBehavior

AjaxBehavior Attributes

Name Default Type Description
listener null MethdExpr Method to process in partial request
immediate false boolean Boolean value that determines the phaseId, when true actions are processed at apply_request_values, when false at invoke_application phase.
async false boolean When set to true, ajax requests are not queued.
process null String Component(s) to process in partial request.
update null String Component(s) to update with ajax.
onstart null String Callback to execute before ajax request is begins.
oncomplete null String Callback to execute when ajax request is completed.
onsuccess null String Callback to execute when ajax request succeeds.
onerror null String Callback to execute when ajax request fails.
global true boolean Global ajax requests are listened by ajaxStatus component, setting global to false will not trigger ajaxStatus
delay null String If less than delay milliseconds elapses between calls to request() only the most recent one is sent and all other requests are discarded. If this option is not specified, or if the value of delay is the literal string none no delay is used.
partialSubmit false boolean Enables serialization of values belonging to the partially processed components only.
disabled false boolean Disables ajax behavior.
event null String Client side event to trigger ajax request.
resetValues false boolean If true, local values of input components to be updated within the ajax request would be reset.
ignoreAutoUpdate false Boolean If true, components which autoUpdate=”true” will not be

Getting Started With AjaxBehavior

Using AjaxBehavior is accomplished by attaching the p:ajax component with the component you want to ajaxify, let’s see the most simple sample that you might used ajax component with.

Following below sample of input component that associated with p:ajax for ajaxifying the input itself. Ajax request has initiated as soon as the keyup event triggered, meanwhile the output component will be updated accordingly.

index.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<title>AjaxBehavior</title>
</h:head>
<h:form>
	<p:inputText id="input" value="#{ajaxBehaviorManagedBean.message}">
		<p:ajax event="keyup" update="output1 output2"></p:ajax>
	</p:inputText>
	<br/>
	<p:outputLabel id="output1" value="Output A :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
	<br/>
	<p:outputLabel id="output2" value="Output B :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
</h:form>
</html>

package com.journaldev.prime.faces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class AjaxBehaviorManagedBean {
	private String message = "";

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

As you’ve noticed above:

  1. AjaxBehavior (p:ajax) component has associated with input component to ajaxify. Typically, it couldn’t be used alone.
  2. Each time the input keyup event triggered, an ajax request is sent to the server. Determination of the type of event you would to consider for triggering passed through using of event property.
  3. For all of those components you would to update accordingly once the response received must be mentioned inside update property in a space delimited expression.
By default, ajax request triggered based on the component it’s associated with. For input components, the trigger should be done once the onchange event happened. For command components, the trigger should be done once the onclick event happened. It’s applicable for you to override the default behaviors by providing event attribute with the DOM action you prefer. In our case, we’ve provided the keyup which makes the ajax triggering happened once the key is released over input element.

Look at the running demonstration below:

AjaxBehavior - Simple Demo

AjaxBehavior’s Listener

Ajax component can be associated with a listener. Listener is a method binding that executed every time in which ajax request has triggered. Below a sample for listening of keyup event.

index.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<title>AjaxBehavior</title>
</h:head>
<h:form>
	<p:inputText id="input" value="#{ajaxBehaviorManagedBean.message}">
		<p:ajax event="keyup" update="output1 output2" listener="#{ajaxBehaviorManagedBean.keyUpListener}"></p:ajax>
	</p:inputText>
	<br/>
	<p:outputLabel id="output1" value="Output A :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
	<br/>
	<p:outputLabel id="output2" value="Output B :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
</h:form>
</html>

package com.journaldev.prime.faces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;

@ManagedBean
@SessionScoped
public class AjaxBehaviorManagedBean {
	private String message = "";

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void keyUpListener(AjaxBehaviorEvent e){
		System.out.println("AjaxBehavior Listener :: "+e.getBehavior()+" :: "+e.getSource());
	}
}

Find out below the output of printed messages into the console at every time the ajax request has initiated. These messages handled by using the listener invocation.

AjaxBehavior - Simple Listener Demo

AjaxBehavior - Simple Listener - Print Out Info

AjaxExceptionHandler

AjaxExceptionHandler is a utility component for built-in ExceptionHandler. Let’s firstly look at its basic info and attributes.

AjaxExceptionHandler Basic Info

Tag ajaxExpectionHandler
Component Class org.primefaces.component.ajaxexceptionhandler.AjaxExceptionHandler
Component Type org.primefaces.component.AjaxExceptionHandler
Component Family org.primefaces.component

AjaxExceptionHandler Attributes

Name Default Type Description
id null String Unique identifier of the component.
rendered true Boolean Boolean value to specify the rendering of the component
binding null Object An el expression that maps to a server side UIComponent instance in a backing bean
onexception null String Client side callback to execute after a exception with this type occured.
update null String Components to update after a exception with this type occured
type null String Exception type to handle.

Getting Started With AjaxExceptionHandler

Before Primfaces 5 release, catching of exceptions and errors was very hard and needs a lot of additional work like browser and jsf lifecycle phases debugging especially when it comes to deal with Ajax.

Most of the developers want to use the ajax mechanism were faced circumstances where everything seems accomplished but even though the ajax request doesn’t trigger. Primefaces 5 provides you a powerful ExceptionHandler out of the box featuring support ajax and non-ajax request. p:ajaxExceptionHandler component to handle ajax exceptions at the same page.

ExceptionHandler and an ElResolver configured is required in the faces configuration file.

faces-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
	<application>
		<el-resolver>
			org.primefaces.application.exceptionhandler.PrimeExceptionHandlerELResolver
		</el-resolver>
	</application>
	<factory>
		<exception-handler-factory>
			org.primefaces.application.exceptionhandler.PrimeExceptionHandlerFactory
		</exception-handler-factory>
	</factory>
</faces-config>

index.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<title>AjaxBehavior</title>
</h:head>
<h:form>
	<p:inputText id="input" value="#{ajaxBehaviorManagedBean.message}">
		<p:ajax event="keyup" update="output1 output2" listener="#{ajaxBehaviorManagedBean.keyUpListener}"></p:ajax>
	</p:inputText>
	<br/>
	<p:outputLabel id="output1" value="Output A :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
	<br/>
	<p:outputLabel id="output2" value="Output B :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
	<br/>
	<p:ajaxExceptionHandler id="exception" type="java.lang.NullPointerException"
	                            update="exceptionPanel" onexception="alert('An Exception Occured ::')"/>

	<p:outputPanel id="exceptionPanel" style="width:500px;height:200px;border:1px;font-size:10px;">
		<p:outputLabel value="Exception Type :: #{pfExceptionHandler.type}"></p:outputLabel>
		<p:outputLabel value="Exception Message :: #{pfExceptionHandler.message}"></p:outputLabel>
		<p:outputLabel value="Exception StackTrace :: #{pfExceptionHandler.formattedStackTrace}"></p:outputLabel>
    </p:outputPanel>
</h:form>
</html>

package com.journaldev.prime.faces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;

@ManagedBean
@SessionScoped
public class AjaxBehaviorManagedBean {
	private String message = "";

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void keyUpListener(AjaxBehaviorEvent e){
		// Print out event information
		System.out.println("AjaxBehavior Listener :: "+e.getBehavior()+" :: "+e.getSource());
		// Throw NullPointerException
		throw new NullPointerException("Anonymous Null Pointer");
	}
}

As you’ve noticed above:

  1. Ajax component associated with a listener for event keyup listening.
  2. The listener will print out the information of the event but it will throw a NullPointerException.
  3. Primefaces exception handler component will detect the exception thrown and it will print out the all information available including the exception stack trace.
  4. onexception property used for provide client side alert once the exception has been thrown. It also could be used for accessing Primefaces components via their WidgetVar and asking them doing some additional work like dialog show or hide.
  5. An implicit object pfExceptionHandler are passed to be accessed by the page, providing the all information about the thrown exception: exception, type, message, stackTrace, formattedStackTrace, timestamp and formattedTimeStamp are the all information you may get from the pfExceptionHandler implicit object.

AjaxBehavior - Exception Handling

AjaxExceptionHandler & Error Pages

ExceptionHandler is integrated with error-page mechanism of Servlet API. At the application startup Primefaces parses the error pages and uses this information to find the appropriate page to redirect to based on the exception type. Now, the same NullPointerException above should be handled through using both of error-page  concept and the implicit object pfExceptionHandler.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5" metadata-complete="true">
	<error-page>
		<exception-type>java.lang.NullPointerException</exception-type>
		<location>/exception.xhtml</location>
	</error-page>
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>
	<context-param>
		<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>
	<listener>
		<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
	</listener>
</web-app>

faces-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
	<application>
		<el-resolver>
			org.primefaces.application.exceptionhandler.PrimeExceptionHandlerELResolver
		</el-resolver>
	</application>
	<factory>
		<exception-handler-factory>
			org.primefaces.application.exceptionhandler.PrimeExceptionHandlerFactory
		</exception-handler-factory>
	</factory>
</faces-config>

index.xml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<title>AjaxBehavior</title>
</h:head>
<h:form>
	<p:inputText id="input" value="#{ajaxBehaviorManagedBean.message}">
		<p:ajax event="keyup" update="output1 output2" listener="#{ajaxBehaviorManagedBean.keyUpListener}"></p:ajax>
	</p:inputText>
	<br/>
	<p:outputLabel id="output1" value="Output A :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
	<br/>
	<p:outputLabel id="output2" value="Output B :#{ajaxBehaviorManagedBean.message}"></p:outputLabel>
</h:form>
</html>

exception.xml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<title>NullPointerException Handler</title>
</h:head>
<h:form>
	<h2>NullPointerExceptionHandler</h2>
	<p:ajaxExceptionHandler id="exception" type="java.lang.NullPointerException"
	                            update="exceptionPanel" onexception="alert('An Exception Occured ::')"/>

	<p:outputPanel id="exceptionPanel" style="width:500px;height:200px;border:1px;font-size:10px;">
		<p:outputLabel value="Exception Type :: #{pfExceptionHandler.type}"></p:outputLabel>
		<p:outputLabel value="Exception Message :: #{pfExceptionHandler.message}"></p:outputLabel>
		<p:outputLabel value="Exception StackTrace :: #{pfExceptionHandler.formattedStackTrace}"></p:outputLabel>
    </p:outputPanel>
</h:form>
</html>

package com.journaldev.prime.faces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;

@ManagedBean
@SessionScoped
public class AjaxBehaviorManagedBean {
	private String message = "";

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void keyUpListener(AjaxBehaviorEvent e){
		// Print out event information
		System.out.println("AjaxBehavior Listener :: "+e.getBehavior()+" :: "+e.getSource());
		// Throw NullPointerException
		throw new NullPointerException("Anonymous Null Pointer");
	}
}

In order to allow your exception displayed into error-page, you should define the error-page into your web.xml and configured your Ajax exception handler to be used. Following below the result of executing the above sample.

AjaxBehavior - Exception Handling - Error Page Mechanism - Index View AjaxBehavior - Exception Handling - Error Page Mechanism - Exception View

As you’ve noticed, custom error-page is used for handling the thrown exception. Implicit pfExceptionHandler is used for providing the displayed information above.

Summary

Multiple components were provided here are used the ajax component to Ajaxify their behaviors. This tutorial spots light into the Ajax lifecycle, AjaxBehavior Primfaces component and the mechanism of handling Ajax exceptions either inside the same page or by using the error-page Servlet API methodology. You should download the final project from the below link and check other attributes to learn more.

Comments

  1. Kura says:

    The xhtml fragments has errors. it’s wrong deployed.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages