一個項目中隻有一個ServletContext對象,我們可以在多個servlet中擷取這個唯一的對象,使用它可以給多個servlet傳遞資料,我們通常成servletContext為上下文對象.這個對象在tomcat啟動時就建立,在tomcat關閉時才被銷毀.有時候我們也把這個對象叫做application.
ServletContext對象的作用就是在整個web應用的動态資源之間共享資料,比如在AServlet中向ServletContext中儲存一個資料,然後在Bservelt中擷取這個資料,這就是共享資料了.
- 擷取ServletContext對象
在servlet中擷取:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//通過servletconfig擷取servletContext
ServletContext servletContext1 = this.getServletConfig().getServletContext();
//直接通過目前對象擷取servletContext對象,這與上面是同一個對象
ServletContext servletContext2 = this.getServletContext();
}
- 作為javaWeb四大域對象之一:具有存取資料的功能
- servletContext.setAttribute("name","zhangSan"): 儲存一個域屬性
- String name=(String)servletContext.getAttribute("name"): 擷取域屬性,傳回值預設為Object類型,需要強轉
- 擷取應用程式初始化參數(即擷取在web.xml中配置的初始化資料)
servlet也可以擷取初始化參數,但它是局部的參數;也就是說,一個Servlet隻能擷取自己的初始化參數,不能擷取别人的,即初始化參數隻為一個Servlet準備!
例如Aservlet隻能擷取Aservlet配置下的初始化參數:
<servlet>
<servlet-name>AServlet</servlet-name>
<servlet-class>com.wang.servlet.AServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>張三</param-value>
</init-param>
</servlet>
而servletContext可以配置公共的初始化參數:
<context-param>
<param-name>name</param-name>
<param-value>李四</param-value>
</context-param>
在doPost方法中擷取代碼為:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContext servletContext2 = this.getServletContext();
String name = servletContext1.getInitParameter("name");
}
- 擷取資源路徑
- 擷取a.txt的真實路徑:String realPath = servletContext.getRealPath(“/a.txt”),realPath的值為a.txt檔案的絕對路徑:F:\tomcat6\webapps\hello\a.txt;
- 擷取b.txt的真實路徑:String realPath = servletContext.getRealPath(“/WEB-INF/b.txt”);
- 擷取資源流
不隻可以擷取資源的路徑,還可以通過ServletContext擷取資源流,即把資源以輸入流的方式擷取:
- 擷取a.txt資源流:InputStream in = servletContext.getResourceAsStream(“/a.txt”);
- 擷取b.txt資源流:InputStream in = servletContext.getResourceAsStream(“/WEB-INF/b.txt”);