【JavaEE笔记】AsyncContext对象与AsycnListener对象

AsyncContext是Servlet3.0中的新特性,用来处理异步请求。

什么是同步与异步区别呢?

它们的区别在于请求的内容是不是立刻返回,同步请求需要等待结果返回后才能继续执行。单线程的执行的时候,需要顺序执行,如果碰到一个计算量很大,很耗时的函数需要执行,该线程就必须在这里等待结果计算出来以后,才能继续执行。

异步请求理论上不需要等待请求的结果,将耗时的计算交给另外一个线程,在结果计算完成后会通知主线程。实际上,异步请求会立刻得到一个临时结果,然后异步请求就可以继续执行了,当异步线程返回真正结果后再通知主线程,然后主线程在做出动作。

使用AsyncContext对象之前,在web.xml要加入如下标签(Servlet相同):

<filter>
       <filter-name>ForwardFilter</filter-name>
       <filter-class>Async.AsyncFilter</filter-class>
       <async-supported>true</async-supported>
 </filter>

在Servlet 3.0中,在ServletRequest上提供了startAsync()方法,多次调用startAsync()返回的是同一个AsyncContext对象

startAsync()方法有参无参的区别是什么呢?

① 没有参数,HttpServletRequest.getRequestURI()返回URI就是dispatch()派发的URL。因为转向不会修改request,getRequestURI()返回最初的URI。

② 含有参数:dispatch()使用的是上一个派发器中URI参数。

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><p></p><pre name="code" class="java">AsyncContext startAsync() throwsjava.lang.IllegalStateException;
AsyncContext startAsync(ServletRequestservletRequest,
                        ServletResponseservletResponse)
                        throwsjava.lang.IllegalStateException
void   dispatch()
void   dispatch(ServletContext context, String path)
void   dispatch(String path)

// Thefollowing sequence illustrates how this will work:

// REQUEST dispatch to /url/A

 AsyncContext ac = request.startAsync();

 ...

 ac.dispatch(); // ASYNC dispatch to /url/A

 

 // REQUEST to /url/A

 // FORWARD dispatch to /url/B

 request.getRequestDispatcher("/url/B").forward(request,response);

 // Start async operation from within the target of the FORWARD

 // dispatch

 ac = request.startAsync();

 ...

 ac.dispatch(); // ASYNC dispatch to /url/A

 

 // REQUEST to /url/A

 // FORWARD dispatch to /url/B

 request.getRequestDispatcher("/url/B").forward(request,response);

 // Start async operation from within thetarget of the FORWARD

 // dispatch

 ac = request.startAsync(request,response);

 ...

 ac.dispatch(); // ASYNC dispatch to /url/B


 
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">AsyncListener对象是用来对AsyncContext对象动作进行监听,使用下面的方法为一个AsyncContext添加一个或者多个Listener。</span>

AsyncContext.addListener(AsyncListener listener)

监听的方法有四个:

public interface AsyncListenerextends EventListener {
   void onComplete(AsyncEvent event) throws IOException;
   void onTimeout(AsyncEvent event) throws IOException;
   void onError(AsyncEvent event) throws IOException;
   void onStartAsync(AsyncEvent event) throws IOException;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值