java asynccontext,从HttpServletRequest获取AsyncContext

I'm using Spring's OncePerRequestFilter overriding shouldNotFilterAsyncDispatch method to return false. This way it can handle asynchronous requests. In the filter I'm trying to do the following:

if (isAsyncDispatch(request)) {

request.getAsyncContext().addListener(new AsyncListener() {

@Override

public void onComplete(AsyncEvent event) throws IOException {

System.out.println("onComplete");

}

@Override

public void onTimeout(AsyncEvent event) throws IOException {

}

@Override

public void onError(AsyncEvent event) throws IOException {

System.out.println("onError");

}

@Override

public void onStartAsync(AsyncEvent event) throws IOException {

}

});

}

So isAsyncDispatch returns true as expected. But when I try getAsyncContext it fails with the following exception:

IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)

Indeed, request.isAsyncStarted() returns false, but request.isAsyncSupported() is true and request.getDispatcherType() is ASYNC.

I don't get: is it async or not? Maybe I'm using the API in a wrong way? How do I add an AsyncListener? Maybe it is because I'm using Tomcat?

Thank you in advance!

解决方案

When I have done this in the past, we have done:

if (request.isAsyncSupported()) {

AsyncContext asyncContext = request.startAsync();

// Do whatever with context

}

The javadoc for getAsyncContext() does state: (in ServletRequest)

IllegalStateException - if this request has not been put into asynchronous mode, i.e., if neither startAsync() nor startAsync(ServletRequest,ServletResponse) has been called

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值