我使用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()
为真且request.getDispatcherType()
为ASYNC
。
我不明白:是不同步?也许我以错误的方式使用API?如何添加AsyncListener
?也许是因为我正在使用Tomcat?
提前谢谢!
答案 0 :(得分:1)
过去我做过这个时,我们已经完成了:
if (request.isAsyncSupported()) {
AsyncContext asyncContext = request.startAsync();
// Do whatever with context
}
getAsyncContext()
的javadoc确实声明:(在ServletRequest)
IllegalStateException - 如果此请求尚未进入异步模式,即,如果既未调用startAsync()也未调用startAsync(ServletRequest,ServletResponse)