Get AsyncContext from HttpServletRequest

若如初见. 提交于 2019-12-07 16:38:22

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/45957127/get-asynccontext-from-httpservletrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!