域對象的作用:保存數據,獲取數據,共享數據
1.九大內置對象:不需要聲明,就可以使用
①、request:就是HTTPServletRequest對象,代表的是客戶端請求,主要是獲取http協議傳輸的數據
②、response:HTTPServletResponse對象,代表的是服務端響應
③、session:HTTPSession對象,代表一次會話
④、application:ServletContext對象,代表當前Web應用
⑤、config:ServletConfig對象,代表當前Servlet,可以獲取當前servlet配置信息
⑥、out:JspWriter對象,把結果輸出到瀏覽器上
⑦、page:指當前jsp對應servlet的引用
⑧、exception:異常對象,可以處理jsp異常
⑨、pageContext:頁面上下文,可以獲取其他8個內置對象
2.jsp頁面上四大域對象
作用域范圍從大到小①>②>③>④
①、application:范圍在當前web應用,只要在一處設置了,當前web應用下的其他地方都可以獲取到
②、session:范圍在一次會話,瀏覽器打開到關閉叫一次會話
③、request:范圍在同一次請求
④、pageContext:范圍在當前頁面
四大域對象的例子:
attr.jsp:使用四個域對象存儲值
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>第一個頁面</h1> <% application.setAttribute("name", "ServletContext"); session.setAttribute("name", "ServletSession"); request.setAttribute("name", "Request"); pageContext.setAttribute("name", "PageContext"); %> <hr> application:<%=application.getAttribute("name") %> <br> session:<%=session.getAttribute("name") %> <br> request:<%=request.getAttribute("name") %> <br> pageContext:<%=pageContext.getAttribute("name") %> <br> <a href="attr1.jsp">下一個頁面</a> </body> </html>
attr1.jsp:獲取存在域對象中的值
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>第二個頁面</h1> application:<%=application.getAttribute("name") %> <br> session:<%=session.getAttribute("name") %> <br> request:<%=request.getAttribute("name") %> <br> pageContext:<%=pageContext.getAttribute("name") %> <br> </body> </html>
一個jsp到另一個jsp
①、application:是在一個web應用中 application可以獲取到值
②、session:范圍在一次會話,瀏覽器打開到關閉叫一次會話 session可以獲取到值
③、request:范圍在同一次請求 因為第一次請求時在訪問attr.jsp,訪問attr1.jsp是第二次請求,request獲取不到值
④、pageContext:范圍在當前頁面 跳轉了頁面,不在一個頁面了,pageContext獲取不到值
運行第一個界面,存值
點擊跳轉下一個頁面,獲取值