Servletconfig和ServletContext

WEB服務器調用Servlet產生的對象:

servletconfig : servlet配置信息

<init-param>  //標籤中的初始化參數
          <init-param>
         <param-name>data</param-name>
          <param-value>xxx</param-value>
           </init-param>

代碼中
獲取指定的Servlet參數:
String value = this.getServletConfig().getInitParameter(“data”);

獲取所有的Servlet參數:
Enumeration e =this.getServletConfig().getInitParameterNames();
while(e.hasMoreElements()){
String name = (String) e.nextElement();
String value = this.getServletConfig().getInitParameter(name);
}
}

開發中存放的參數有:字符集,數據庫連接信息…

ServletContext 域對象,域即是整個應用程序。提供了有關servlet運行環境的詳細信息,用於與容器通信。
web容器啓動時爲web應用程序創建的一個對象,代表當前web應用,上下文,可以實現Servlet的數據共享。

Servlet中獲取ServletContext
ServletContext context = this.getServletContext();

主要用途

設置參數和獲取參數
setAttribute(“data”,data);
getAttribute(“data”);

web.xml中配置web應用的初始化參數

context-param
param-namedata/param-name
param-value>xx/param-value
/context-param:

轉發Servlet
this.getServletContext().getRequestDispatcher(“/servlet/servlet01”).forward(request,response);

獲取項目的資源文件

//獲取webcontent下的資源
String path = this.getServletContext().getRealPath("/test.txt");

// 截取文件名
String fileName = path.substring(path.lastIndexOf("\\") + 1);

// 輸出文件名
response.getOutputStream().write(fileName.getBytes());
發佈了75 篇原創文章 · 獲贊 37 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章