版權聲明:本文為部落客原創文章,轉載請注明出處。 https://blog.csdn.net/twilight_karl/article/details/75804749
簡介
隐式對象是_jspService()中的局部變量,故隻能在
<% %>
和
<%= %>
中使用
隐式對象
說明 | |
---|---|
out | JspWriter對象,内部關聯PrintWriter對象 |
request | 對應HttpServletRequest對象 |
response | 對應HttpServletResponse對象 |
config | 對應ServletConfig |
application | 對應ServletContext |
session | 對應HttpSession |
pageContext | 對應PageContent對象。将所有JSP頁面資訊封裝起來,可以通過pageContext獲得所有的隐式對象 |
exception | 對應Throwable對象,代表由其他JSP頁面抛出的一場對象,隻會出現在JSP錯誤頁面 |
page | 對應轉譯後的this |
使用pageContext可以擷取所有隐式對象,也可以通路 page、request、session、application範圍的變量。
request = pageContext.getRequest();
response = pageContext.getResponse();
config = pageContext.getServletConfig();
application = pageContext.getServletContext();
session = pageContext.getSession();
out = pageContext.getOut();
常用方法:
- setAttribute(String name, String value, int scope):如果沒有指定scope,該屬性預設在page範圍内
- getAttribute(String name, int scope) 獲得屬性值
- removeAttribute(String name, int scope) 移除屬性
- findAttribute()依次從頁面、請求、會話、應用程式範圍查找有無對應的屬性
查找範圍(scope)
- pageContext.APPLICATION_SCOPE ServletContext(application)
- pageContext.REQUEST_SCOPE request
- pageContext.SESSION_SCOPE session
- pageContext.PAGE_SCOPE pageContext
<%
pageContext.setAttribute("scope", "page");
session.setAttribute("scope", "session");
application.setAttribute("scope", "application");
request.setAttribute("scope", "request");
%>
page:<%= pageContext.getAttribute("scope", pageContext.PAGE_SCOPE) %><br/>
session:<%= pageContext.getAttribute("scope", pageContext.SESSION_SCOPE) %><br/>
application:<%= pageContext.getAttribute("scope", pageContext.APPLICATION_SCOPE) %><br/>
request:<%= pageContext.getAttribute("scope", pageContext.REQUEST_SCOPE) %><br/>
錯誤處理
錯誤界面隻有iserrorPage為true時才可以使用exception對象
發生錯誤的頁面 hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page errorPage="Error.jsp" %>
<html>
<body>
<%=1/0 %>
</body>
</html>
錯誤頁面 error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<html>
<body>
<h1>這是一個錯誤界面</h1>
<%=exception %>
<hr/>
</body>
</html>
error-page
如果希望容器在發現某個錯誤或者異常時,自動轉發至錯誤頁面,則可以使用
<error-page></error-page>
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/JSPTest/Error.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/JSPTest/Error.jsp</location>
</error-page>