我正在使用Spring的覆盖OncePerRequestFilter
的shouldNotFilterAsyncDispatch
方法返回false。这样,它可以处理异步请求。在过滤器中,我尝试执行以下操作:
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
时,它失败,但出现以下异常:IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. 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)