【问题标题】:Cancel Request with browser使用浏览器取消请求
【发布时间】:2014-02-20 21:35:58
【问题描述】:
假设这种情况:我从浏览器(firefox)向我的服务器(apache tomcat)发送一个请求。响应来自服务器大约 2 分钟后。如何以我的服务器无法继续做出响应的方式取消此请求?
当用户向服务器发送请求时,通常会转到应用程序的另一个链接(或菜单或取消请求),对于开发人员来说取消这些情况非常重要,从而减少服务器负载。
好的,我想要一种技术来检测发送到我的服务器的此类传入请求并取消为客户端做出响应的所有操作(因为客户端不再等待服务器响应)。
我在谷歌和堆栈中找不到有用的信息。
我还在 server.xml 中设置了 keep-alive-timeout,但什么也没发生!
我也阅读了这个主题 cancle request ,但它对我没有帮助。
所以请帮我解决这个问题...
【问题讨论】:
标签:
java
apache
http
tomcat
web-applications
【解决方案1】:
您可以取消将内容发送到其输出流的请求(并刷新它)。
如果用户取消请求,servlet 将失去与浏览器的连接,然后向输出流发送内容将引发 ClientAbortException 使进程停止。
试试这个:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
try {
out.println("<!DOCTYPE html>");
out.println("<html><body>");
out.println("<h1 id=\"count\"></h1>");
for (int i = 0; i < 60; i++) {
Thread.sleep(1000);
out.print("<script>document.getElementById(\"count\").innerHTML=\"" + i + "\";</script>");
out.flush();
System.out.println(i);
}
out.println("</body></html>");
} catch (Exception ex) {
System.out.println("Stoped due to " + ex.toString());
} finally {
out.close();
}
}