Java Servlet 3.0 異步支持實例

jopen 11年前發布 | 46K 次閱讀 Servlet Java開發

Servlet 3.0中包含了一些重要的新特性。其中包含異步支持。 在這里,我們將看到如何配置一個異步的servlet。

Objective:

  • How to code Java Async Servlet?
  • </ul>

    Environment & Tools:

    • JDK 1.7
    • Eclipse (or other IDE)
    • Maven (optional)
    • </ul>

      Library:

      • Java Servlet API 3.0
      • </ul>

        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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!