Servlet學習筆記(3)——ServletContext

  1. 定義

    servlet引擎爲每個web應用程序都創建一個對應的ServletContext對象,它被包含在ServletConfig對象中,調用ServletConfig.getServletContext方法可以返回ServletContext對象的引用。

注:由於一個web應用程序中的所有Servlet都共享同一個ServletContext對象,所以,ServletContext對象也被稱爲application對象(web應用程序對象)。

    可以獲取當前應用的各方面信息

2.  功能

1)獲取當前web應用的初始化參數

設置初始化參數:可以被所有的servlet獲取,而servlet的初始化參數只用那個servlet可以獲取。

ServletContext的初始化參數設置節點在<web-app>節點裏面,與<servlet>節點並列,如

 <context-param>
      <param-name>driver</param-name>
      <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  <context-param>
      <param-name>jdbcUrl</param-name>
      <param-value>jdbc:mysql:///atguigu</param-value>
  </context-param>
  
  <!-- 配置和映射servlet -->
  <servlet>
      <servlet-name>HelloServlet</servlet-name>
      <servlet-class>day_0206.HelloServlet</servlet-class>

2)獲取當前web應用的某一個文件在服務器上的絕對路徑:getRealPath(String path);

wKiom1idZfzxfgseAAI8yz6RnUg488.png-wh_50

使用getRealPath()方法如

		String realPath = servletContext.getRealPath("/note.txt");
		System.out.println(realPath);

效果:輸出

E:\JavaWorkSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\day_0206\note.txt


3)獲取當前web應用的名稱:getContextPath()

String contextPath = servletContext.getContextPath();
		System.out.println(contextPath);

輸出

/day_0206


4)獲取當前web應用的某一個文件對應的輸入流:getResourceAsStream(String path),path的 / 相當於當前應用的根目錄,如

		try {
			ClassLoader classLoader = getClass().getClassLoader();
			InputStream is = classLoader.getResourceAsStream("test.txt");
			System.out.println("1: " + is);
			
			InputStream is2 = servletContext.getResourceAsStream("/WEB-INF/classes/test.txt");//必須用根目錄來定位,否則如用“servletContext.getResourceAsStream("test.txt")”則輸出null
			System.out.println("2: " + is2);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

輸出結果

1: java.io.BufferedInputStream@156d9dd

2: java.io.FileInputStream@12734c2


5)和attribute相關的幾個方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章