|
| 1 | +package com.hmkcode; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import javax.servlet.AsyncContext; |
| 6 | +import javax.servlet.AsyncEvent; |
| 7 | +import javax.servlet.AsyncListener; |
| 8 | +import javax.servlet.ServletException; |
| 9 | +import javax.servlet.annotation.WebServlet; |
| 10 | +import javax.servlet.http.HttpServlet; |
| 11 | +import javax.servlet.http.HttpServletRequest; |
| 12 | +import javax.servlet.http.HttpServletResponse; |
| 13 | + |
| 14 | + |
| 15 | +@WebServlet(name="asyncServlet",value = {"/async"},asyncSupported = true) |
| 16 | +public class AsyncServlet extends HttpServlet |
| 17 | +{ |
| 18 | + |
| 19 | +private static final long serialVersionUID = 1L; |
| 20 | + |
| 21 | + @Override |
| 22 | + protected void doGet(HttpServletRequest req, HttpServletResponse resp) |
| 23 | + throws ServletException, IOException { |
| 24 | + |
| 25 | + final AsyncContext ctx = req.startAsync(); |
| 26 | + |
| 27 | + ctx.setTimeout(3000); |
| 28 | + |
| 29 | + ctx.addListener(new AsyncListener() { |
| 30 | + |
| 31 | + @Override |
| 32 | + public void onTimeout(AsyncEvent arg0) throws IOException { |
| 33 | + System.out.println("onTimeout..."); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public void onStartAsync(AsyncEvent arg0) throws IOException { |
| 38 | + System.out.println("onStartAsync..."); |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public void onError(AsyncEvent arg0) throws IOException { |
| 43 | + System.out.println("onError..."); |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public void onComplete(AsyncEvent arg0) throws IOException { |
| 48 | + System.out.println("onComplete..."); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + |
| 53 | + ctx.start(new Runnable() { |
| 54 | + @Override |
| 55 | + public void run() { |
| 56 | + // TODO Auto-generated method stub |
| 57 | + try { |
| 58 | + ctx.getResponse().getWriter().write("Async Started..."); |
| 59 | + } catch (IOException e) { |
| 60 | + e.printStackTrace(); |
| 61 | + } |
| 62 | + |
| 63 | + ctx.complete(); |
| 64 | + } |
| 65 | + }); |
| 66 | + } |
| 67 | +} |
0 commit comments