AsyncContext and startAsync() Example in Servlet 3.0
February 14, 2014
javax.servlet.AsyncContext is an interface introduced in Servlet 3.0. AsyncContext has the role to start asynchronous context within a servlet using HttpServletRequest.startAsync() method. We can divide our task for asynchronous execution. Within a servlet, some of the task can be performed by another servlet or jsp and some of the task cam be done by parent servlet itself and finally response will be sent collectively. AsyncContext is started by
Request object as below
AsyncContext asyncContext = request.startAsync();
To divide the task of parent servlet I am calling a JSP which will execute other task. For this AsyncContext provides dispatch() method. We can use it as below
asyncContext.dispatch("/asynctest.jsp");
1. JDK 7
2. Tomcat 7
3. Eclipse
AsyncContextExample.java
package com.concretepage.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.AsyncContext; 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(asyncSupported = true, value = "/AsyncContextExample", loadOnStartup = 1) public class AsyncContextExample extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{ doGet(request,response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(0); ServletRequest servReq = asyncContext.getRequest(); boolean b = servReq.isAsyncStarted(); out.println("isAsyncStarted : "+b); asyncContext.dispatch("/asynctest.jsp"); out.println("<br/>asynchronous task finished."); } }
asynctest.jsp
<head> <body> <br/> JSP response: Asynchronous Example </body> </head>

How to use AsyncContext.complete()
While using complete() method, we should not use dispatch() method. Code snippet will look as below.AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(0); ServletRequest servReq = asyncContext.getRequest(); boolean b = servReq.isAsyncStarted(); out.println("isAsyncStarted : "+b); asyncContext.complete(); out.println("asynchronous task finished.");