天天看點

ServletContext1、ServletContext是伺服器端一塊公共的存儲區域,可供所有開戶存儲資料,全局區域。2、在servlet中擷取ServletContext3、設值、取值、删除4、用處:5、servletContext生命周期,和伺服器同生共死。6、Request、Session、ServletContext/aoolication

1、ServletContext是伺服器端一塊公共的存儲區域,可供所有開戶存儲資料,全局區域。

一個web應用程式隻有一個ServletContext。

2、在servlet中擷取ServletContext

ServletContext servletContext = this.getServletContext();
ServletContext servletContext1 = req.getSession().getServletContext();
           

3、設值、取值、删除

servletContext.setAttribute("name", "books");
servletContext.getAttribute("name");
servletContext.removeAttribute("name");
           

4、用處:

a)可以讀取全局配置檔案

<context-param>
  	<param-name>name</param-name>
  	<param-value>yuchao</param-value>
  </context-param>
           

Servlet中代碼:

ServletContext ct = this.getServletContext();
String value = ct.getInitParameter("name");
           

b)  讀取資源檔案

資源檔案放于根目錄下 和WEB-INF同級

InputStream in = ct.getResourceAsStream("db.properties");
Properties pro = new Properties();
pro.load(in);
out.print(pro.getProperty("driver")+"<br/>");
out.print(pro.getProperty("url")+"<br/>");
           

如果資源在src下:

//類加載器
		InputStream in = MyServletContext.class.getClassLoader().getResourceAsStream("db.properties");
		Properties pro = new Properties();
		pro.load(in);
		out.print(pro.getProperty("driver")+"<br/>");
		out.print(pro.getProperty("url")+"<br/>");
           

c)   作為全局變量的運用;網站計數器,網絡聊天室

5、servletContext生命周期,和伺服器同生共死。

6、Request、Session、ServletContext/aoolication

存放時間長短:

ServletContext最長,和伺服器一樣

Session次子,在一個會話範圍(失效時間)

Request 請求範圍