您好,登錄后才能下訂單哦!
定義
servlet引擎為每個web應(yīng)用程序都創(chuàng)建一個對應(yīng)的ServletContext對象,它被包含在ServletConfig對象中,調(diào)用ServletConfig.getServletContext方法可以返回ServletContext對象的引用。
注:由于一個web應(yīng)用程序中的所有Servlet都共享同一個ServletContext對象,所以,ServletContext對象也被稱為application對象(web應(yīng)用程序?qū)ο螅?/p>
可以獲取當(dāng)前應(yīng)用的各方面信息
2. 功能
1)獲取當(dāng)前web應(yīng)用的初始化參數(shù)
設(shè)置初始化參數(shù):可以被所有的servlet獲取,而servlet的初始化參數(shù)只用那個servlet可以獲取。
ServletContext的初始化參數(shù)設(shè)置節(jié)點在<web-app>節(jié)點里面,與<servlet>節(jié)點并列,如
<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)獲取當(dāng)前web應(yīng)用的某一個文件在服務(wù)器上的絕對路徑:getRealPath(String path);
使用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)獲取當(dāng)前web應(yīng)用的名稱:getContextPath()
String contextPath = servletContext.getContextPath(); System.out.println(contextPath);
輸出
/day_0206
4)獲取當(dāng)前web應(yīng)用的某一個文件對應(yīng)的輸入流:getResourceAsStream(String path),path的 / 相當(dāng)于當(dāng)前應(yīng)用的根目錄,如
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(); }
輸出結(jié)果
1: java.io.BufferedInputStream@156d9dd
2: java.io.FileInputStream@12734c2
5)和attribute相關(guān)的幾個方法
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。