Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get AsyncContext from HttpServletRequest

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!

like image 681
Dmitry Senkovich Avatar asked May 12 '26 05:05

Dmitry Senkovich


1 Answers

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

like image 89
adamcooney Avatar answered May 13 '26 20:05

adamcooney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!