1、内置对象的来历
JSP是由一些内置对象的,即不需要定义,也不需要我们主动创建,就可以直接使用的对象。当然,其对象名称也是固定的,无法修改,我们可以直接调用其相关方法。
在 [01] JSP的基本认识 已经说过JSP的本质,并明白了其运行的流程,容器会帮我们将JSP翻译成为Java类,其中会有一些“固定”代码,我们还是先看其核心方法:
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,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
//我们自定义的Java代码会被翻译到这个位置
} 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);
}
}
可以看到,在方法的开头中定义了一系列变量,在 try catch 块中对变量进行了赋值。根据容器翻译JSP文件的流程我们知道,我们自定义的Java代码都是加载在“固定”代码之后,也就是变量赋值之后,所以我们完全可以使用该方法体中内部定义的变量,以及方法的参数,并且可以顺利执行。
于是我们常用的JSP内置对象就这么有了:
类型 | 变量名 | 备注 |
HttpServletRequest | request | |
HttpServletResponse | response | |
PageContext | pageContext | JSP上下文对象,可以由此获取其他内置对象 |
HttpSession | session | |
ServletContext | application | |
ServletConfig | config | |
JspWriter | out | 可以像客户端输出内容,然而<%= %>更便捷 |
Object | page | page = this 指翻译后当前类的对象,很少使用 |
Throwable | exception | 错误页面才可使用 |
注:在某个页面抛出异常时(需页面定义 errorPage="xxx.jsp"),将转发至JSP错误页面。提供exception对象是为了在JSP中进行处理,只有在错误页面中才可以使用该对象。所以如果是作为错误页面则必须定义 <%@page isErrorPage="true" %>
那么内置对象的使用也很简单,直接在JSP页面的<% %>中嵌入即可,如 <%=request.getParameter("title)%>
至于内置对象的作用域,从他们的类型来说,已经不言而喻了,详情可以参考Servlet部分的作用域知识点。