因为我们所提到的out不是指System.out,而是一个包装我们JSP页面的有效方法中的变量。 System.out会将内容写入servlet容器的控制台(通常是日志文件);而out则是完全不同的类别,它会将内容写入生成的响应的输出流中。
当JSP转换为代码时,它(理论上,且在Tomcat中实际上)会经过两个步骤: JSP -> servlet源代码,然后servlet源代码 -> 类。整个页面将被放入一个方法中,使用Tomcat看起来就像这样:
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
"qdforumerror.jsp", true, 65536, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
/* =============================================
...your <% ... %> JSP code here, with
any markup outside those tags converted into
out.print("..."); statments...
=============================================
*/
}
catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
}
finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
正如您所看到的,out是该方法内部的一个变量,类型为JspWriter(而不是像System.out一样的OutputStream)。
(副注:您在<%! ... %>标记中包含的代码不是放在该方法中,而是放在生成的servlet类的其他位置。)