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