【发布时间】:2014-04-18 13:28:25
【问题描述】:
我有以下 Async Servlet、相应的 Listener 和 AsyncProcessor 类
AsyncProcessor.java:
public class AsyncProcessor implements Runnable {
private AsyncContext asyncContext;
public AsyncProcessor(AsyncContext asyncContext, String view) {
this.asyncContext = asyncContext;
this.asyncContext.getRequest().setAttribute("dispatch", view);
}
public void run() {
try {
Thread.sleep(10*1000);
asyncContext.complete();
} catch(Exception e) {
}
}
}
MyServlet13.java:
@WebServlet(name="myServlet13", urlPatterns="/servlet13", asyncSupported=true)
public class MyServlet13 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext asyncContext = request.startAsync();
System.out.println("Before starting Async processing");
asyncContext.addListener(new MyAsyncListener());
Executor executor = (Executor)getServletContext().getAttribute("executor");
asyncContext.start(new AsyncProcessor(asyncContext, "/jsp13.jsp"));
System.out.println("After starting Async processing");
}
}
MyAsyncListener.java:
public class MyAsyncListener implements AsyncListener {
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
System.out.println("This is from onStartAsync");
}
public void onComplete(AsyncEvent asyncEvent) throws IOException {
System.out.println("This is from onComplete, before dispatch");
AsyncContext asyncContext = asyncEvent.getAsyncContext();
asyncContext.dispatch("/jsp13.jsp");
asyncContext.getResponse().getWriter().println("Async tasks completed...<br>");
System.out.println("This is from onComplete, after dispatch");
}
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
System.out.println("This is from onTimeout");
}
public void onError(AsyncEvent asyncEvent) throws IOException {
System.out.println("This is from onError");
}
}
当我尝试使用 /servlet13 url 模式调用 MyServlet13 时,我得到以下异常
java.lang.IllegalStateException : 调用 [asyncDispatch()] 对具有异步状态 [COMPLETING] 的请求无效
不知道这段代码有什么问题
根据 servlet3.0 规范,我们可以将 AsyncListeners 添加到获得的AsyncContext
它将能够监听各种事件。在我的例子中,onComplete() 应该被监听,并且请求应该被发送到 jsp13.jsp 视图(我的网络应用上下文中确实有 jsp13.jsp)
我正在使用最新版本的 tomcat 7.0.x 和 servlet 3.0 规范
【问题讨论】:
-
有趣的是,有时我会遇到错误,有时会出现空白页
仅供参考,AsyncListener 的 onComplete() 被调用,我能够看到“这是来自 onComplete,在调度后" 在服务器控制台上
标签: servlets tomcat7 java-ee-6 servlet-3.0 asynchronous