Java Servlet 3.0 异步支持实例

jopen 11年前

Servlet 3.0中包含了一些重要的新特性。其中包含异步支持。 在这里,我们将看到如何配置一个异步的servlet。

Objective:

  • How to code Java Async Servlet?

Environment & Tools:

  • JDK 1.7
  • Eclipse (or other IDE)
  • Maven (optional)

Library:

  • Java Servlet API 3.0

This Sample:
We will send 5 jquery.ajax request to the async servlet. These requests will run 5 threads that will stay on hold until we send a request with “exit” parameter.

( 1 ) Async Servlet

We will use @WebServlet to define the servlet instead of using web.xml file.

package com.hmkcode;     import java.io.IOException;     import javax.servlet.AsyncContext;  import javax.servlet.AsyncEvent;  import javax.servlet.AsyncListener;  import javax.servlet.ServletException;  import javax.servlet.annotation.WebServlet;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;     @WebServlet(name="asyncServlet",value = {"/async"},asyncSupported = true)  public class AsyncServlet extends HttpServlet  {     private static final long serialVersionUID = 1L;         String param ="";       @Override      protected void doGet(HttpServletRequest req, HttpServletResponse resp)          throws ServletException, IOException {            // 1.0 start async         final AsyncContext ctx = req.startAsync();         param = ctx.getRequest().getParameter("seq");            // 2.0 set the timeout         ctx.setTimeout(0);            // 3.0 add listener         ctx.addListener(new AsyncListener() {                 @Override              public void onTimeout(AsyncEvent arg0) throws IOException {                  System.out.println("onTimeout...");                          }                 @Override              public void onStartAsync(AsyncEvent arg0) throws IOException {                  System.out.println("onStartAsync...");                           }                 @Override              public void onError(AsyncEvent arg0) throws IOException {                  System.out.println("onError...");                        }                 @Override              public void onComplete(AsyncEvent arg0) throws IOException {                  System.out.println("onComplete...");              }         });            // 4.0 run a thread         ctx.start(new Runnable() {              @Override              public void run() {                   try {                           // hold until receive exit                        while(!param.equals("exit")){}                           ctx.getResponse().getWriter().write(ctx.getRequest().getParameter("seq"));                     } catch (IOException e) {                      e.printStackTrace();                  }                  ctx.complete();              }            });     }  }

We need 4 steps to make our async servlet.

  1. Get AsyncContext
  2. Set TimeOut (optional)
  3. Add Listener
  4. Call AsyncContext.start()

 ( 2 ) Client Side

This part is just providing a way to send some request to the async servlet.

索引.png

( 3 ) Run Sample Code

Using Maven we can run this sample code as following:

>mvn jetty:run

 Souce Code @ GitHub