servlet context 和 servlet config,servletcontext
servletConfig
Servlet容器初始化一個servlet對象時,會為這個servlet對象建立一個servletConfig對象,該對象中包含了servlet的<init-param>初始化參數資訊。Servlet容器在調用servlet對象的init(ServletConfig config)方法時,會把servletConfig對象當做參數傳遞給servlet對象。Init(ServletConfig config)方法中通過this.config=config將ServletConfig對象儲存,之後在service方法中可以通過this.getServletConfig()擷取該對象。如果要覆蓋 init() 方法,應調用 super.init() 以確保該Servlet得到正確地初始化。
作用:將資料庫資訊、編碼方式等配置資訊放在web.xml中,以後修改時不需要修改原始碼。
常用方法:
- String getServletName() ,擷取當前Servlet在web.xml中配置的名字
- String getInitParameter(String name),擷取當前Servlet指定名稱的一個初始化參數的值
- Enumeration getInitParameterNames() ,擷取當前Servlet所有初始化參數的名字組成的枚舉
- ServletContext getServletContext() ,擷取代表當前web應用的ServletContext對象
一般開發人員建立的Servlet都繼承HttpServlet,而HttpServlet是GenericServlet的子類。GenericServlet也實現了getInitParameter()方法,因此Servlet可以直接調用該方法去擷取servlet的配置資訊,不用通過ServletCofig對象。
ServletContext
容器啟動後,會為每一個Web應用建立唯一的一個符合ServletContext介面要求的對象---servlet context。只要不關閉伺服器或刪除web應用,該servlet context就一直存在。
作用:Web應用範圍記憶體取共用資料;訪問web應用的資源檔;Servlet對象之間通過ServletContext對象來實現通訊;擷取Servlet容器的相關資訊;訪問日誌資訊等。
GenericServlet/ServletConfig/HttpSession/FilterConfig都提供了getServletContext()方法擷取ServletContext對象。
綁定資料時,在滿足使用條件的情況下,優先使用生命週期短的,提高記憶體使用量率:
request<session<Context
常用方法:
- getAttribute(String name) ,擷取綁定在servlet context上的資料。
- getInitParameter(String name) ,擷取<context-param>標籤中為整個Web應用配置的初始化參數。
- getInitParameterNames() ,一次性擷取<context-param>裡所有的初始化參數名
- getRealPath(String path) ,擷取應用程式內指定資源的絕對路徑。
- getResource(String parh),path必須是/開頭,代表當前web應用程式的根目錄。返回一個代表某個資源的URL對象。
- getResoutceAsStream(String parh),可以使用相對於根目錄的路徑訪問到web目錄下的所有檔案,而不必知道絕對路徑,返迴文件流。
//一次性擷取Context裡所有的初始化參數Enumeration enumeration = context.getInitParameterNames();while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); String value = context.getInitParameter(name); System.out.println(name + ";" + value);}常用概念區分:
- 請求參數 parameter:瀏覽器發送過來的請求中的參數資訊
- 初始化參數 initparameter:在web.xml中為Servlet或ServletContext配置的初始化資訊
- 域屬性 attribute:四大範圍中存取的索引值對