天天看點

ServletContext(Servlet上下文對象)作用 生命周期

servletcontext(servlet上下文對象)

容器提供的對象

作用:

1.相對路徑轉換為絕對路徑

string path = "/mp3/1.jpg";

servletcontext ctx = getservletcontext();

string realpath = ctx.getrealpath(path);

file file = new file(realpath);

2.可以擷取容器的附加資訊。

容器名稱

容器版本

servlet規範的版本号

3.全局容器

user user = new user();

string str = "";

int i=100;

ctx.setattribute("a1",user);

ctx.setattribute("a2",str);

ctx.setattribute("a3",i);

user user = (user)ctx.getattribute("a1");

servletcontext生命周期,容器啟動時自動建立該對象,容器關閉時容器銷毀該對象。

做什麼工作?

不放業務資料。

1,系統的配置資訊。如:

資料庫的使用者名和密碼。上傳檔案的路徑。

2,讀取web.xml配置檔案中關于servlet初始化參數的方法:

servletconfig config = getservletconfig();

string value = config.getinitparameter("key");

練習1:

修改昨天的下檔案代碼,改成相對路徑方式。

練習2:

編寫一個自啟動servlet,讀取properties檔案中的配置資訊,并放到全局容器中。編寫一個測試servlet來讀取全局容器中的配置資訊。

練習3:

編寫一個servlet,用戶端通路這個servlet的時候得到一個excel表格。使用字元流的方式完成。

上一篇: json 簡介
下一篇: Cookie和Session