jsp九大內置對象經常使用方法及四個做用域

九大內置對象

jsp中的九大內置對象是自帶的,不須要new 也能使用的對象java

out:

print(),println( )方法tomcat

輸出對象,向客戶端輸出內容服務器

request:

請求對象,存儲「客戶端向服務端發送的請求信息」
request對象的常見方法:cookie

  • String getParameter(String name) :根據請求的字段名key (input標籤的name屬性值) ,返回字段值value (input標籤的value屬性值)
  • String[] getParameterValues(String name):根據請求的字段名key ,返回多個字段值value (checkbox)
  • void setCharacterEncoding("編碼格式utf-8") :設置post方式的請求編碼 (tomcat7之前默認iso-8859-1,tomcat8之後改成了utf-8)
  • getRequestDispatcher("B.jsp").forward(request,response) :請求轉發 的方式跳轉頁面 A - > B
  • ServletContext getServerContext():獲取項目的ServletContext對象
  • Cookie getCookies():獲取一個cookie對象
  • void setAttribute(String name,Object obj):設置屬性值(新增,修改)
  • Object getAttribute(String name):根據屬性名,查找屬性值

response:

響應對象session

response對象的常見方法:app

  • void addCookie( Cookie cookie ), 服務端向客戶端增長cookie對象
  • void sendRedirect(String location ) throws IOException :頁面跳轉的一種方式(重定向)
  • void setContetType(String type):設置服務端響應的編碼(設置服務端的contentType類型)

session:

會話對象,session存儲在服務端jsp

實現機制:客戶端第一次請求服務端時,服務端會產生一個session對象(用於保存該客戶的信息),而且每一個session對象 都會有一個惟一的 sessionId( 用於區分其餘session),且產生一個cookie,而且該cookie的name=JSESSIONID ,value=服務端sessionId的值;而後服務端會在響應客戶端的同時將該cookie發送給客戶端post

客戶端第二次請求服務端時,服務端會先用客戶端cookie種的JSESSIONID 去服務端的session中匹配sessionid,若是匹配成功(cookie jsessionid和sesion sessionid),說明此用戶 不是第一次訪問,無需登陸;性能

session對象的常見方法:this

  • String getId() :獲取sessionId
  • boolean isNew() :判斷是不是 新用戶(第一次訪問)
  • void invalidate():使session失效 (退出登陸、註銷)
  • void setAttribute(String name,Object obj):設置屬性值(新增,修改)
  • Object getAttribute(String name):根據屬性名,查找屬性值
  • void setMaxInactiveInterval(秒) :設置最大有效 非活動時間
  • int getMaxInactiveInterval():獲取最大有效 非活動時間

application:

全局對象

application對象的常見方法:

  • String getContextPath() :虛擬路徑
  • String getRealPath(String name):絕對路徑(虛擬路徑 相對的絕對路徑)
  • void setAttribute(String name,Object obj):設置屬性值(新增,修改)
  • Object getAttribute(String name):根據屬性名,查找屬性值

pagecontext:

JSP頁面容器

  • void setAttribute(String name,Object obj):設置屬性值(新增,修改)
  • Object getAttribute(String name):根據屬性名,查找屬性值

config:

配置對象(服務器配置信息)

page:

當前JSP頁面對象(至關於java中的this)

exception:

異常對象

四個做用域

四種範圍對象 做用域
pageContext (page對象) 請求數據當前頁面有效
request 請求對象 請求數據同一次請求有效,(重定向後無效)
session 會話對象 請求數據同一次會話有效
appliation 全局對象 請求數據全局有效(整個項目有效)

以上4個對象共有的方法:

  • Object getAttribute(String name):根據屬性名,查找屬性值

  • void setAttribute(String name,Object obj) :設置屬性值(新增,修改)

  • setAttribute("a","b") ;//若是a對象以前不存在,則新建一個a對象 ;若是a以前已經存在,則將a的值改成b

  • void removeAttribute(String name):根據屬性名,刪除對象

注意:儘可能使用最小的範圍。由於對象的範圍越大,形成的性能損耗越大。

相關文章
相關標籤/搜索