从HttpServletRequest获取AsyncContext [英] Get AsyncContext from HttpServletRequest
问题描述
我正在使用Spring的 OncePerRequestFilter
覆盖 shouldNotFilterAsyncDispatch
方法返回false。这样它就可以处理异步请求。在过滤器中我尝试执行以下操作:
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 {
}
});
}
所以 isAsyncDispatch
返回如预期的那样。但是当我尝试 getAsyncContext
时,它失败并出现以下异常:
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)
确实, request.isAsyncStarted()
返回false,但 request.isAsyncSupported()
为true且 request.getDispatcherType()
是 ASYNC
。
Indeed, request.isAsyncStarted()
returns false, but request.isAsyncSupported()
is true and request.getDispatcherType()
is ASYNC
.
我不明白:是不同步?也许我以错误的方式使用API?如何添加 AsyncListener
?也许是因为我正在使用Tomcat?
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?
提前谢谢你!
推荐答案
当我在过去做过这个时,我们已经完成了:
When I have done this in the past, we have done:
if (request.isAsyncSupported()) {
AsyncContext asyncContext = request.startAsync();
// Do whatever with context
}
<$ c的javadoc $ c> getAsyncContext()确实状态:(在 ServletRequest )
IllegalStateException - 如果此请求尚未进入异步模式,即,如果既没有调用startAsync()也没有调用startAsync(ServletRequest,ServletResponse)
IllegalStateException - if this request has not been put into asynchronous mode, i.e., if neither startAsync() nor startAsync(ServletRequest,ServletResponse) has been called
这篇关于从HttpServletRequest获取AsyncContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!