# ServletContext
### 基本概述
????servletContext接口是Servlet中最大的一個接口,呈現了web應用的Servlet視圖。ServletContext實例是通過?getServletContext()方法獲得的,由于HttpServlet繼承GenericServlet的關系,GenericServlet類和HttpServlet類同時具有該方法。
????每個應用都會有一個ServletContext對象與之關聯,當容器分布在在多個虛擬機上時,web應用在所分布的每個虛擬機上都擁有一個ServletContext實例.缺省情況下,ServletContext不是分布式的,并且只存在于一個虛擬機上。
參考文檔:[http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html](http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html)
?
### ServletContext原理圖

PS:一個WEB服務器上所有的Servlet共享一個ServletComtext。
?
### 小結
1、ServletContext?是在服務器
2、ServletContext?是被所有客戶端共享
3、ServletContext?是當web應用啟動的時候,自動創建
4、ServletContext?當web應用關閉/tomcat關閉/對web應用reload?會造成servletContext銷毀
5、ServletContext?與?Session、Request一樣都能存入屬性、取出屬性,但是其作用域和生命周期是不同的
????1、ServletContext作用域是整個WEB應用,生命周期是從服務器啟動到關閉
????2、Session作用域是對應的會話,生命周期是從會話創建到會話銷毀
????3、Request作用域是一次響應,生命周期是一次響應(服務器將HTTP響應發給瀏覽器)
#### 6、ServletContext能夠通過以下幾種方式使用
????1、獲取
???????this.getServletConfig().getServletContext();
????????this.getServletContext(); //兩種效果一樣,推薦下面這種
????2、添加屬性
????????this.getServletContext().setAttribute(String,Object);
????3、取出屬性
????????this.getServletContext().getAttribute(屬性名);
????4、移除屬性??//注意:痛Session、Request一樣,移除屬性只能一個一個移除
????????this.getServletContext().removeAttribute(屬性名);
?
### ServletContext應用
#### 1、獲取WEB應用的初始化參數
~~~
<!-- 如果希望所有的servlet都可以訪問該配置. -->
<context-param>
<param-name>name</param-name>
<param-value>scott</param-value>
</context-param>
~~~
如何獲取
~~~
String val= this.getServletContext().getInitParameter("name");
~~~
#### 2、使用ServletContext實現跳轉
~~~
//目前我們跳轉到下一個頁面
//1 response.sendRedirect("/web應用名/資源名");
//2 request.getRequestDispatcher("/資源名").forward(request, response);
/*
* 區別1. getRequestDispatcher 一個跳轉發生在web服務器 sendRedirect發生在瀏覽器
* 2. 如果request.setAttribute("name","Switch") 希望下一個頁面可以使用屬性值,則使用 getRequestDispatcher
* 3. 如果session.setAttribute("name2","Switch2"), 希望下一個頁面可以使用屬性值,則兩個方法均可使用,但是建議使用 getRequestDispatcher
* 4. 如果我們希望跳轉到本web應用外的一個url,應使用sendRedirect
*/
//3.這種方法和2一樣
this.getServletContext().getRequestDispatcher("/資源url").forward(request, response);
~~~
#### 3、讀取文件,和獲取文件全路徑
~~~
//首先讀取到文件
InputStream inputStream=this.getServletContext().getResourceAsStream("dbinfo.properties");
//創建Properties
Properties pp=new Properties();
pp.load(inputStream);
out.println("name="+pp.getProperty("username"));
//如果文件放在src目錄下,應該使用類加載器來讀取
//InputStream is=Servlet5.class.getClassLoader().getResourceAsStream("dbinfo.properties");
//獲取文件全路徑
//讀取到一個文件的全路徑
String path=this.getServletContext().getRealPath("/imgs/Sunset.jpg");
out.println("paht = "+path);
~~~
----------參考《韓順平.細說Servlet》