使用Spring的WebAsyncTask异步请求时出现如下错误:
java.lang.IllegalStateException: Cannot forward after response has been committed
java.lang.IllegalStateException: Can't set AsyncWebRequest with concurrent handling in progress
org.springframework.web.util.NestedServletException: Request processing failed;
Caused by: java.lang.IllegalStateException: Can't set AsyncWebRequest with concurrent handling in progress
at org.springframework.util.Assert.state(Assert.java:392)
at org.springframework.web.context.request.async.WebAsyncManager.setAsyncWebRequest(WebAsyncManager.java:108)
表面上看错误描述并不清楚。这里我仅仅记录我的解决方法,我这里是因为时间超时引起的。也许你也是这样的情况:
原代码结结构如下:
@RequestMapping(value = { "/webAsyncTask/test" })
public WebAsyncTask test(HttpServletRequest request) {
Callable<String> callable = new Callable<String>() {
public String call() throws InterruptedException {
String string = new String();
Thread.sleep(15000);
return string;
}
};
return new WebAsyncTask(callable);
}
这里直接返回的new WebAsyncTask(callable)报错。我是通过设置超时时间解决的:返回new WebAsyncTask(60000, callable);
注意:即使设置里超时时间而没做超时处理,这样是不严谨的。因为当60000毫秒之后call()没执行完依然会报异常。Spring对超时处理提供有WebAsyncTask.onTimeout()方法。
所有我最终的代码结构如下:
@RequestMapping(value = { "/webAsyncTask/test" })
public WebAsyncTask test(HttpServletRequest request) {
Callable<String> callable = new Callable<String>() {
public String call() throws InterruptedException {
String string = new String();
Thread.sleep(15000);
return string;
}
};
WebAsyncTask asyncTask = new WebAsyncTask(60000, callable);
asyncTask.onTimeout(new Callable<String>() {
public String call() throws Exception {
String string = "请求超时!";
return string;
}
});
return asyncTask;
}