JSP 隐式对象

九个内置对象的作用、作用域,以及各自最常用的方法。

Beginner
Key Points九个隐式对象不用声明就能用,因为容器在 _jspService 开头替你赋值了。

九个对象

ObjectTypeUse
requestHttpServletRequest请求参数、头、属性
responseHttpServletResponse状态码、响应头
outJspWriter输出内容
sessionHttpSession会话数据
applicationServletContext全应用共享数据
configServletConfig初始化参数
pageContextPageContext访问其他对象与各作用域
pageObject当前 Servlet 实例,相当于 this
exceptionThrowable仅 isErrorPage="true" 时可用

四个作用域

JSP
<%
    pageContext.setAttribute("a", "只在当前页");       // page
    request.setAttribute("b", "当前请求");             // request
    session.setAttribute("c", "当前会话");             // session
    application.setAttribute("d", "整个应用");         // application
%>

<%-- 取值时按 page → request → session → application 顺序找 --%>
<p>${a} / ${b} / ${c} / ${d}</p>

EL ${x} searches all four scopes from narrowest to widest. To be explicit use ${sessionScope.c} or ${applicationScope.d} — essential when names collide.

pageContext 的特殊能力

JSP
<%
    // 取到其他隐式对象
    HttpServletRequest r = (HttpServletRequest) pageContext.getRequest();

    // 转发与包含
    pageContext.forward("/a.jsp");
    pageContext.include("/parts/footer.jsp");

    // 按名字直接读任意作用域
    Object v = pageContext.findAttribute("user");

    // 指定作用域写
    pageContext.setAttribute("msg", "hi", PageContext.SESSION_SCOPE);
%>

out 与 response.getWriter

The JSP out is a buffered JspWriter. Writing to response.getWriter() directly interleaves with it, because out's buffer has not flushed yet. Use a single output channel in a JSP.

exception exists only on pages declaring <%@ page isErrorPage="true" %>. Using it elsewhere fails to compile with "cannot find symbol" — a very common beginner trap.

Friends & Partners