Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Servlets Servlet3 AsyncListener Example

Related Tutorials


 
 

Share on Google+Share on Google+

AsyncListener Example

Advertisement
In this section, you will learn about registering AsyncListener with the recently created AsyncContext with an example.

AsyncListener Example

In this section, you will learn about registering AsyncListener with the recently created AsyncContext with an example.

The AsyncListener will be notified when an asynchronous events occurs.

Need of AsyncListener

AsyncEvent contains the details of the event occurred by the asynchronous processes. These events includes successfully completion of asynchronous cycle, times out, or results in an error . The AsyncListener will receive an AsyncEvent (asynchronous event object) when the above events(i.e. completion of asynchronous cycle, times out, or results in an error) occurs.

The AsyncListener will be notified in their creation/addition order.

EXAMPLE

In the given below example, AsyncListener MyAsyncListener is added to AsyncContext in the AsyncContextCompleteMethod.java class using addListener() method. On different asynchronous  events, MyAsyncListener  is notified through AsyncEvent object. MyAsyncListener displays the logged information on the console.

MyAsyncListener.java

package roseindia;

import java.util.logging.Logger;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;

public class MyAsyncListener implements AsyncListener {
private static final Logger logger = Logger.getLogger("net.roseindia");

// Public constructor is required by servlet spec
public MyAsyncListener() {
}

public void onComplete(AsyncEvent ae) {
logger.info("AsyncListener: onComplete for request: "
+ ae.getAsyncContext().getRequest().getAttribute("ServletName"));
}

public void onTimeout(AsyncEvent ae) {
logger.info("AsyncListener: onTimeout for request");
}

public void onError(AsyncEvent ae) {
logger.info("AsyncListener: onError for request: ");
}

public void onStartAsync(AsyncEvent ae) {
logger.info("AsyncListener: onStartAsync");
}
}

AsyncContextCompleteMethod.java

package roseindia;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/AsyncListenerExample", asyncSupported = true)
public class AsyncListenerExample extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

Date date = new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("<h2>AsyncContext Example </h2>");
request.setAttribute("receivedAt", date);
out.println("Request Time :" + request.getAttribute("receivedAt"));
//Starting AsyncContext
AsyncContext asyncCtx = request.startAsync();
ServletRequest req = asyncCtx.getRequest();

req.setAttribute("ServletName", "AsyncListenerExample");

//adding AsyncListener named as 'MyAsyncListener'
asyncCtx.addListener(new MyAsyncListener());

asyncCtx.setTimeout(1000);

boolean bol2 = req.isAsyncSupported();
// This will return true
out.println("<br>AsyncSupported : " + bol2);

boolean bol = req.isAsyncStarted();

// This will return true
out.println("<br>AsyncStarted : " + bol);

if (bol) {
asyncCtx.dispatch("/asyncOutput.html");
}

boolean bol1 = req.isAsyncStarted();

// This will return false
out.println("<br>AsyncStarted : " + bol1);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

asyncListenerOutput.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Asynchronous Servlet 3.0 Example</title>
</head>
<body>
<h3>Given above the Servlet 3.0 AsyncListener example</h3>
</body>
</html>

OUTPUT

When you execute the above code, you will get the following output :

http://localhost:8080/Servlet3Examples/AsyncListenerExample

In console, you will get the following output :

INFO: Server startup in 376 ms
Jun 19, 2012 1:40:15 PM roseindia.MyAsyncListener onComplete
INFO: AsyncListener: onComplete for request: AsyncListenerExample              

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 25, 2012

Related Tutorials

Discuss: AsyncListener Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com