Saturday, January 19, 2013

Servlet 3.0 ( Asynchronous Support for Web )



In Servlet 3.0 one can create Asynchronous servlets /Filters . Detach request/response from thread.

3 ways to set asyn servlets support

  • < async-supported > true < async-supported >
  • or by annotations @WebServlet(asyncSupported = true,name = "HelloAnnotationServlet", urlPatterns = {"/helloanno"})
  • or by configuring dynamically while registering servlet .. ServletRegistration.Dynamic.setAsyncSupported(true);


see an example here  https://blogs.oracle.com/enterprisetechtips/entry/asynchronous_support_in_servlet_3 
 Important interfaces for Async web apps are 

1 . interface AsyncContext 
An AsyncContext is created and initialized by a call to ServletRequest.startAsync() or ServletRequest.startAsync(ServletRequest, ServletResponse). Repeated invocations of these methods will return the same AsyncContext instance, reinitialized as appropriate.
In the event that an asynchronous operation has timed out, the container must run through these steps:
  1. Invoke, at their onTimeout method, all AsyncListener instances registered with the ServletRequest on which the asynchronous operation was initiated.
  2. If none of the listeners called complete() or any of the dispatch() methods, perform an error dispatch with a status code equal to HttpServletResponse.SC_INTERNAL_SERVER_ERROR.
  3. If no matching error page was found, or the error page did not call complete() or any of the dispatch() methods, call complete().
  4. There are 3 flavors of dispatch() for AsyncContext.
 void dispatch()
          Dispatches the request and response objects of this AsyncContext to the servlet container.
 void dispatch(ServletContext context, java.lang.String path)
          Dispatches the request and response objects of this AsyncContext to the given path scoped to the given context.
 void dispatch(java.lang.String path)
          Dispatches the request and response objects of this AsyncContext to the given path.


No comments: