从HttpServletRequest获取AsyncContext

我正在使用Spring的OncePerRequestFilter重写shouldNotFilterAsyncDispatch方法来返回false。 这样它就可以处理异步请求。 在filter中我试图执行以下操作:

 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 { } }); } 

所以isAsyncDispatch按预期返回true。 但是,当我尝试getAsyncContext它失败并出现以下exception:

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

实际上, request.isAsyncStarted()返回false,但request.isAsyncSupported()为true, request.getDispatcherType()ASYNC

我不明白:它是异步还是不同步? 也许我以错误的方式使用API​​? 如何添加AsyncListener ? 也许是因为我正在使用Tomcat?

先感谢您!

当我过去这样做时,我们已经完成了:

 if (request.isAsyncSupported()) { AsyncContext asyncContext = request.startAsync(); // Do whatever with context } 

getAsyncContext()的javadoc确实状态:(在ServletRequest中 )

IllegalStateException – 如果此请求尚未进入异步模式,即,如果既未调用startAsync()也未调用startAsync(ServletRequest,ServletResponse)