将该部分单独拧出来,方便查看
3.3 异步的支持
3.3.1 AsyncContext接口
ServletRequest执行startAsync()或者startAsync(ServletRequest, ServletResponse) 进入异步模式,将会创建一个AsyncContext,将其需要异步的操作放在此AsyncContext中
addListener(AsyncListener listener)//可以增加监听器
3.3.2 ServletRequest接口
startAsync(ServletRequest, ServletResponse)
将当前请求/响应 或指定请求/响应 放到异步模式中
3.3.3 AsyncListener异步监听器
| void | onComplete |
|
| onError |
|
| onStartAsync |
|
| onTimeout Notifies this AsyncListener that an asynchronous operation has timed out. |
可以给AsyncContext实例增加一个AsyncListener监听器,当AsyncContext调用complete()完成后即可触发onComplete(e)方法
3.3.4 例子
asyncSupported要定义为true
3.3.4.1简单例子
@WebServlet(name = "syncServlet", value = { "/syncServlet"},asyncSupported=true)
publicclass SyncTestServlet extends HttpServlet {
privatestaticfinallongserialVersionUID = -126107068129496624L;
publicvoid 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;
}
publicvoid 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();//完成异步操作
}
}
推荐阅读
代码之余轻松一下:当前热门-人民的名义
理解异步请求在Servlet中的实现
本文详细解释了在Servlet中使用异步请求的概念、关键接口和监听器的运用,通过实例展示了如何在Servlet中引入异步操作,并在主线程和子线程间高效交互。了解如何利用异步请求提高用户体验和服务器效率。
1544

被折叠的 条评论
为什么被折叠?



