Java Reference
In-Depth Information
Asynchronous servlets rely on a basic improvement in Hypertext Transfer Protocol (HTTP) 1.1,
which enabled persistent connections. In HTTP 1.0, each connection is used to send and receive
only a single request and response couple; however, HTTP 1.1 allowed web applications to keep
the connection alive and to send multiple requests. On a standard implementation, the Java back
end would need a separate thread constantly attached to the HTTP connection. However, Java
nonblocking I/O (NIO) APIs recycle threads between active requests, thanks to the new NIO
capability. Today all web servers compatible with the Servlet 3.0 specii cation have built‐in support
for Java NIO. Why do you need such behavior from servlets? The nature of back‐end systems
involves lengthy operations such as connecting to other servers, performing complex calculations,
and making transactional database operations. However, the nature of web pages requires quite the
opposite. Web users expect fast response times and a functional UI even if back‐end operations are
completed. AJAX addressed this issue for the browser and started the Web 2.0 revolution.
Servlet 3.0 introduced the startAsync() method, which enabled asynchronous operations.
Listing 9‐3 shows an example.
LISTING 9‐3: An example of the startAsync() method
package com.devchronicles.asynchronous;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(urlPatterns={"/async"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
final AsyncContext asyncContext = req.startAsync();
final String data;
asyncContext.addListener(new AsyncListener() {
@Override
public void onComplete(AsyncEvent event) throws IOException {
AsyncContext asyncContext = event.getAsyncContext();
asyncContext().getWriter().println(data);
}
@Override
public void onTimeout(AsyncEvent event) throws IOException {
// Code not shown for brevity
}
@Override
public void onError(AsyncEvent event) throws IOException {
// Code not shown for brevity
}
continues
Search WWH ::




Custom Search