JSP 隐式对象
九个内置对象的作用、作用域,以及各自最常用的方法。
Key Points九个隐式对象不用声明就能用,因为容器在 _jspService 开头替你赋值了。
九个对象
| Object | Type | Use |
|---|---|---|
| request | HttpServletRequest | 请求参数、头、属性 |
| response | HttpServletResponse | 状态码、响应头 |
| out | JspWriter | 输出内容 |
| session | HttpSession | 会话数据 |
| application | ServletContext | 全应用共享数据 |
| config | ServletConfig | 初始化参数 |
| pageContext | PageContext | 访问其他对象与各作用域 |
| page | Object | 当前 Servlet 实例,相当于 this |
| exception | Throwable | 仅 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.九个对象
| 对象 | 类型 | 用途 |
|---|---|---|
| request | HttpServletRequest | 请求参数、头、属性 |
| response | HttpServletResponse | 状态码、响应头 |
| out | JspWriter | 输出内容 |
| session | HttpSession | 会话数据 |
| application | ServletContext | 全应用共享数据 |
| config | ServletConfig | 初始化参数 |
| pageContext | PageContext | 访问其他对象与各作用域 |
| page | Object | 当前 Servlet 实例,相当于 this |
| exception | Throwable | 仅 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} 会自动按这四个作用域从小到大搜索。想明确指定作用域就写 ${sessionScope.c}、${applicationScope.d}——同名变量时这能避免取错。
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
JSP 的 out 是带缓冲的 JspWriter。往 response.getWriter() 直接写会打乱顺序——因为 out 的缓冲还没刷出去,两股输出会交错。在 JSP 里只用一个输出口。
exception 只在 <%@ page isErrorPage="true" %> 的页面存在。普通页面里用它编译就报「找不到符号」——这是新手最常踩的一个坑。