1 Web應用共享數據區ServletContext接口
ServletContext接口表示一個web應用的上下文。可以想象成一個web一個能用的共享數據區域,該區域保存整個web共享數據。
1.1 Servlet容器何時創建ServeltContext接口實現類
當一個web應用啟動的時候,就會創建該ServletContext接口的實現類。我們可以在根據需求,讀寫ServletContext這個web共享區的數據,那么如何獲得ServletContext這個實例呢?下面提供了兩種方法
1.2 如何獲得ServletContext接口實例
方法1:
可以通過ServletConfig接口的getServletContext()方法獲得
方法2:
通過GenericServlet抽象類的getServletContext()方法獲得,不過這個方法其實也是調用了ServletConfig的getServletContext()方法
在GenericServlet.java中
- public ServletConfiggetServletConfig(){
- return config;
- }
- public ServletContextgetServletContext(){
- return getServletConfig().getServletContext();
- }
ServletConfig接口:
- public interface ServletConfig
- {
- public abstract StringgetlnitParameter(Stringname); //取得servlet起始參數值(string)
- public abstract EnumerationgetlnitParameterNames(); //取得servlet起始參數名稱(Enumeration)
- public abstract ServletContextgetServletContext(); //取得servletcontext對象(servletcontext)
- public abstract string getservletname(); //取得servle的名稱(string)
- }
public interface ServletConfig
ServletConfig :從一個servlet被實例化后,對任何客戶端在任何時候訪問有效,但僅對servlet有效,一個servlet的ServletConfig對象不能被另一方面個servlet訪問。
ServletContext:真正全局對象。
在web.xml中
下面就相當于一個ServletConfig對象。
-
<
init-param
>
-
<
param-name
>
Copration
</
param-name
>
-
<
param-value
>
DongDong
</
param-value
>
-
</
init-param
>
- < init-param >
- < param-name > Copration </ param-name >
- < param-value > DongDong </ param-value >
- </ init-param >
通過 ServletConfig 對象的
public String getInitParameter(String name); 或
public Enumeration getInitParameterNames();
方法來取得你已經配置好的參數,也就是說,你對
servlet的配置都已經記錄在ServletConfig對象中了
。
結論:你對Servlet的配置,在Servlet的初始化時都由容器來收集并且記錄到ServletConfig的實現類中。
轉自:
http://lewis-q.iteye.com/blog/161814
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
