Servlet AsyncEvent and AsyncListener

tutorial and example
tutorial and example

AsyncEvent

AsyncEvent is an asynchronous event class responsible to generate events. This class is present in javax.servlet package.

This event occurs when various asynchronous tasks operating on ServletRequest get completed, expired or generate errors. ServletRequest is initiated by calling startAsync() method of ServletRequest type.

Method of AsyncEvent

              Method

               Description

AsyncContext getAsyncContext()

This method is used to initialize AsyncEvent.

ServletRequest getSuppliedRequest()

This method returns the ServletRequest which is used to initialize AsyncEvent. If ServletRequest is not used to  initialize AsyncEvent then it returns null.

ServletResponse getSuppliedResponse()

This method returns the ServletResponse which is used to initialize AsyncEvent. If ServletResponse is not used to  initialize AsyncEvent then it returns null.

Throwable getThrowable()

This method returns the Throwable which is used to initialize AsyncEvent. If Throwable is not used to  initialize AsyncEvent then it returns null

AsyncListener

AsyncListener is an Asynchronous Listener Interface used to indicate that event is occurred. This interface is also present in javax.servlet package.

It notifies that event occurs for asynchronous tasks operating on ServletRequest when listener has been added gets completed, expired or generates errors.

Methods of AsyncListener

Following are the methods provided by AsyncListener.

            Method

                    Description

void onComplete(AsyncEvent event)

This method indicates that an asynchronous operation has been completed.

void onError(AsyncEvent event)

This method indicates that an asynchronous operation generates an error.

void onStartAsync(AsyncEvent event)

This method indicates that a startAsync() method of ServletRequest type is invoked to generate new asynchronous cycle.

void onTimeout(AsyncEvent event)

This method indicates that an asynchronous operation has been expired.

Example of Asynchronous Event and Listener

DemoServlet.java

Output: