JSP翻譯引擎在將JSP翻譯成servlet的過程中, 在servlet里預(yù)先定義了九個對象, 因此我們可以在JSP頁面中直接使用這九個對象
類型 | 對象 |
---|---|
Servlet(this) | page |
Request | request |
Response | response |
ServletConfig | config |
ServletContext | application |
Session | session |
exception | |
out | |
pageContext |
1.out
相當(dāng)于response.getWriter();
區(qū)別在于out對象自帶緩沖區(qū), 如果out和response.getWriter()混用可能會造成輸出順序上混亂
page指令中buffer和autoflush就是用來設(shè)置out緩沖區(qū)的
總結(jié)起來一句話, 如果想要在JSP頁面中輸出內(nèi)容, 直接使用out, 盡量別使用response.getWriter();
2.pageContext
代表當(dāng)前JSP頁面的運行環(huán)境的對象, 通過該對象可以訪問頁面中的共享數(shù)據(jù)
PageContext對象功能:
(1) 作為入口對象獲取其他八大隱式對象
方法名 | 返回值 |
---|---|
getPage()方法 | 返回page隱式對象 |
getRequest()方法 | 返回request隱式對象 |
getResponse()方法 | 返回response隱式對象 |
getServletConfig()方法 | 返回config隱式對象 |
getServletContext()方法 | 返回application隱式對象 |
getSession()方法 | 返回session隱式對象 |
getException()方法 | 返回exception隱式對象 |
getOut()方法 | 返回out隱式對象 |
(2) 本身也是一個域?qū)ο? 也可以作為入口對象來操作其他三大作用域中的數(shù)據(jù)
a)本身是個域?qū)ο?/strong>
setAttribute(String name, Object obj);
getAttribute(String name);
removeAttribute(String name);
getAttributeNames();
生命周期: 訪問JSP頁面開始時創(chuàng)建, 訪問JSP頁面結(jié)束時銷毀
作用范圍: 當(dāng)前JSP頁面
主要功能: 在當(dāng)前JSP頁面中共享數(shù)據(jù)
ServletContext > Session > request > pageContext
b)作為入口對象, 可以操作其他三大作用域
setAttribute(String name, Object value,int scope)
getAttribute(String name,int scope)
removeAttribute(String name,int scope)
其中pageContext中代表域的常量:
PageContext.APPLICATION_SCOPE
PageContext.SESSION_SCOPE
PageContext.REQUEST_SCOPE
PageContext.PAGE_SCOPE
額外提供了:
findAttribute(String name); //按照由小到大的順序在四大作用域中搜尋指定名稱的屬性, 如果找到就返回, 如果都找不到就返回一個null
ServletContext > session > request > pageContext
(3) 提供了便捷方法實現(xiàn)請求轉(zhuǎn)發(fā)和包含
request.getRequestDispatcher("/7.jsp").forward(request, response);
request.getRequestDispatcher("/7.jsp").include(request, response);
<%@include file="xxx.jsp" %>
轉(zhuǎn)發(fā): pageContext.forward("/index.jsp");
包含: pageContext.include("/index.jsp");