JSP编程- response.getWriter().flush();不起作用

3
<%
response.getWriter().write("Hello world<BR>\n");
response.getWriter().flush();
wait(10000); // 10 seconds
response.getWriter().write("Goodbye happiness.<BR>\n");
%>

期望结果:浏览器中显示“Hello World”。10秒后,显示“Goodbye happiness.”。

实际情况:页面在加载10秒钟后,最终显示“Hello World Goodbye Happiness”。

我想做的是在达到不同的里程碑时显示长时间运行操作的状态。这可能吗?

我正在使用Windows 7上的Eclipse EE(带Tomcat)。


听起来你应该真的使用ajax来完成这个。 - Matt Ball
3个回答

3
<html>
<body>
 You didn't tell us which browser you were using. Chrome and Firefox behave as you   expect them to do. 
But, IE needs some filler at the start of the page. IE will wait for a certain amount of content to render.
I am testing with IE8 and this works for me.
<br/>
<%
   out.print("Hello world<br/>");
   out.flush();
   Thread.sleep(3000); // 3 seconds for easy testing.
   out.print("Goodbye happiness.");
 %>
 </body>
 </html>

1
我认为这里的问题是wait(10000); // 10 seconds。不确定您看到了什么响应,但在执行wait()之前必须先锁定。您应该将wait(10000);行更改为以下之一:
synchronized (this){
    wait(10000); //10 secs
}

或者

Thread.sleep(10000);

即使如此,如果它仍然无法正常工作,您应该检查是否有任何东西覆盖了写入器并缓冲数据直到关闭。

出于好奇,"必须获取锁"的根本原因是什么? - Thorbjørn Ravn Andersen

0

在编写内容之前,您必须设置“Transfer-Encoding: chunked”标头。

response.setHeader("Transfer-Encoding", "chunked");

如果未设置内容长度,则不是有效的答案。服务器将默认设置它。 - Ramesh PVK
这取决于服务器配置。如果设置了"content length not set then Transfer-Encoding: chunked",则可能会被覆盖。 - Clivant Yeo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接