我有以下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规范
答案 0 :(得分:0)
嗯,这不会起作用。您已完成申请,无法再次发送。 complete()结束你的周期,响应已经发送。