在JSP页面有关out.flush()异常

来源:百度知道 编辑:UC知道 时间:2024/05/19 20:56:06
<%
int i = 1;
try {
while (true) {
out.print("<h1>"+(i++)+"</h1>");
out.flush();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
out.print("<h1>11"+e+"</h1>");
}
}
} catch (Exception e) {
e.printStackTrace();
out.print("<h1>222"+e+"</h1>");
}
%>
当用TOMCAT启动项目的时候
JSP页面就会产生这样的一个异常:
java.io.IOException: Illegal to flush within a custom tag
后台打印出异常为:
java.io.IOException: Illegal to flush within a custom tag
at javax.servlet.jsp.tagext.BodyContent.flush(BodyContent.java:80)
at org.apache.jsp.default_jsp._jspService(default_jsp.java:152)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
at javax.servlet.http.HttpServlet.service(HttpServlet.

在JSP的<%%>中不可以out.flush()来冲掉前面output。
在Servlet中可以用out.flush()这么做。(但你让那个主Thread停顿3秒没有错误,apache catalina会在output时候停3秒)

虽然说JSP本质就是Servlet,但那其实是JSP页在第一次访问后被Compile成Java servlet class,此时JSP才等于Servlet。

而JSP页面中每一行,在Complile的时候,都相当于out.println();(比如:JSP中有一行<title>abc</title>, 那么其对应的Compile之后的Servlet必定有一行out.println("<title>abc</title>");)

所以,如果你在JSP中用out.flush不但但会冲掉你自己的output,还会导致之前所有的<DOCTYPE...><html><head>...这些都被冲掉,如此会使JSP缺少很多output,所输出网页就非常不完整。所以catalina不允许你这么做。