1. 程式人生 > >ServletContext、ServletConfig 物件

ServletContext、ServletConfig 物件

ServletContext 物件

作用:
解決了 不同使用者 的資料共享問題

作用域:整個專案內

生命週期:伺服器啟動到伺服器關閉

特點:
伺服器進行建立、使用者共享、一個專案只有一個

原理:
ServletContext 物件由伺服器進行建立,一個專案只有一個ServletContext 物件。不管在專案的任意位置進行獲取得到的都是同一個物件,那麼不同使用者發起的請求獲取到的也就是同一個物件了,該物件由使用者共同擁有。

使用:
獲取 ServletContext 物件

/*以下三種方式獲取的都是同一個ServletContext 物件*/
ServletContext context1 = this.getServletContext(); //第一種方式(常用) ServletContext context2 = this.getServletConfig().getServletContext(); //第二種方式 ServletContext context3 = req.getSession().getServletContext(); //第三種方式

使用作用域進行共享資料流轉

context.setAttribute("message", "我是一個ServletContext物件");		//資料儲存

//另一個Servlet中寫
context.getAttribute("message"); //資料獲取
  • 注意:
    不同的使用者可以給ServletContext物件進行資料的存取
    獲取的資料不存在返回null

獲取 web.xml 中的全域性配置的全域性資料的值

<!-- 作用:將靜態資料和程式碼進行解耦 -->
<context-param>
	<param-name>鍵名</param-name>
	<param-value>小李</param-value>
</context-param>
String str =
context.getInitParameter("鍵名"); String str = context.getInitParameterNames(); //返回鍵名的列舉

獲取 webContext 下專案資源流物件

InputStream is = context.getResourceAsStream("/doc/a.txt");	

獲取 webContext下資源絕對路徑

String path = context.getRealPath("/doc/a.txt");		//動態獲取該檔案的絕對路徑

案例:網頁瀏覽器次數統計
在成功登入時,建立計數器並自增,然後儲存到ServletContext物件中。
在主介面中取出計數器的資料並顯示。

ServletConfig 物件

作用:
ServletConfig 物件是 Servlet 的專屬配置物件,每個 Servlet 都單獨擁有一個 ServletConfig 物件,用來獲取 web.xml 中的配置資訊。

使用:
獲取 ServletConfig 物件

<servlet>
	<param-name>config</param-name>
	<param-value>urf-8</param-value>
</servlet>
ServletConfig config = this.getServletConfig();		//獲取 ServletConfig 物件
String code = config.getInitParameter("config");		//獲取 web.xml 中 servlet 的配置資訊