閱讀404 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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.全局容器
ServletContext ctx = getServletContext();
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表格。使用字符流的方式完成。

最後更新:2017-04-03 15:21:51

  上一篇:go servlet小結 請求轉發和重定向的區別
  下一篇:go Cookie和Session