ServletRequest执行startAsync()或者startAsync(ServletRequest, ServletResponse) 进入异步模式,将会创建一个
AsyncContext,将其需要异步的操作放在此
AsyncContext中
addListener(AsyncListener listener)//可以增加监听器
startAsync
(ServletRequest, ServletResponse)
将当前请求/响应 或指定请求/响应 放到异步模式中
void |
onComplete |
|
onError |
|
onStartAsync |
|
onTimeout Notifies this AsyncListener that an asynchronous operation has timed out. |
可以给AsyncContext实例增加一个AsyncListener监听器,当AsyncContext调用complete()完成后即可触发onComplete(e)方法
asyncSupported要定义为true
@WebServlet(name = "syncServlet", value = { "/syncServlet"},asyncSupported=true)
public class SyncTestServlet extends HttpServlet {
private static final long serialVersionUID = -126107068129496624L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" Servlet Start:::<br>This is ");
out.print(this.getClass());
out.println("<br>using the GET method<br>");
out.flush();
//-------------增加一个异步线程
System.out.println("主response对象:"+response);
AsyncContext sc = request.startAsync(request,response);
Thread t = new Thread(new MyThread(sc));
t.start();
//-------------继续主线程
//注:主线程不需要等待子线程完毕,可以先执行并打印出来【异步进行】
out.println(" -------Servlet end.");
out.flush();
}
}
class MyThread extends Thread{
private AsyncContext syncContext;
public MyThread(AsyncContext syncContext){
this.syncContext = syncContext;
}
public void run(){
System.out.println("MyThread start2....");
HttpServletResponse resp = (HttpServletResponse) syncContext.getResponse();
System.out.println("MyThread end2....");
try {
PrintWriter out = resp.getWriter();
out.println("<br><br>-----MyThread start----");
out.println("<br>-----wait running.....");
out.flush();//flush即可先输出,不需要等全部完成
System.out.println("子线程里的response对象(和主线程是同一个):"+resp);
Thread.sleep(3000);
out.println("<br>-----MyThread end----");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
//out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
syncContext.complete();//完成异步操作
}
}