Servlet中Response的flushBuffer()是怎么用的?
Response的flushBuffer()的用法
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
马克-to-win:response有个buffer,flushBuffer()会强行把Buffer的内容写到客户端浏览器。(Forces any content in the buffer to be written to the client. ),如果你不flushBuffer的话,当程序运行到最后的右大括号的时候,Tomcat也会把Response的Buffer的东西,一次性发给客户端。这就是在我们前面的hello world Servlet的例子当中,没有加flushBuffer的原因。
例:3.2.1
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String myN = request.getParameter("myName");
PrintWriter pw = response.getWriter();
for (int i = 0; i < 5; i++) {
pw.println("back is " + myN);
/*下面两种flush方法的效果完全一样。后面的close方法针对他们俩都起效。
*/
// pw.flush();
response.flushBuffer();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*上面的两种flush,只要加上下面一句close,之后的东西都打印不出来了。但也不报错。*/
// pw.close();
pw.println("Mark-to-win Finished");
}
}
浏览器里面的输出结果是:(一共打印了五遍。遍与遍的间隔是两秒。)
back is Mark-to-win back is Mark-to-win back is Mark-to-win back is Mark-to-win back is Mark-to-win Mark-to-win Finished