JSP常用对象来源分析
在开发JSP程序时,我们可以直接用out对象进行输出,用request对象获取属性值,session保持会话状态等,那这些对象是从何而来的呢?当浏览器请求一个xx.jsp文件时,web服务器首先会把jsp文件编译成HttpJspBase的子类xx_jsp,然后调用其_jspService方法(如果已编译则跳过编译这一步,xx_jsp的_jspService方法包括了我们书写的所有jsp代码。在此方法的前面部分,此方法已帮我们把out、session、application等对象初始化好,而jsp代码放于后面部分,所以我们在jsp中就可以很方便的使用out、session、application等对象)
如果使用Tomcat,可以在\work\Catalina\localhost\web模块\org\apache\jsp下查看jsp编译后的Java文件
_jspServie方法示例:
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { //jsp页面默认可以使用的对象(还包括方法参数中的request、response对象) JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request); if (exception != null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; //jsp 页面编译后的代码 out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write(" <title>Error</title>\r\n"); out.write("</head>\r\n"); out.write("\r\n"); out.write("<body>\r\n"); out.write(" Bussiness logic exception, please try later...\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); }}
页:
[1]