gpt4 book ai didi

java - 从 HttpServletRequest 获取 AsyncContext

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:34 25 4
gpt4 key购买 nike

我正在使用 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()异步

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

提前致谢!

最佳答案

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

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

getAsyncContext() 的 javadoc 声明:(在 ServletRequest 中)

IllegalStateException - if this request has not been put into asynchronous mode, i.e., if neither startAsync() nor startAsync(ServletRequest,ServletResponse) has been called

关于java - 从 HttpServletRequest 获取 AsyncContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45957127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com