8 ServletContext
?
1 為什么需要ServletContext 技術
顯示網站多少人在線,顯示當前登錄者是第幾位登錄者等信息。
?
2?什么是ServletContext
可以把它想象成一個服務器上的公共空間,每個用戶都可以訪問到它。 Web 容器在啟動時,它會為每個Web 應用程序都創建一個對應的ServletContext對象,它代表當前web應用。
① ServletContext 在服務器端
② ServletContext 被所有客戶端共享
③ ServletContext 當Web應用啟動時,自動創建
④ web應用關閉/tomcat關閉/reload,ServletContext自動消亡
?
3 創建
ServletContext 對象可以通過 getServletConfig().getServletContext()方法獲得,也可以通過this.getServletContext()獲得。
?
4 刪除
ServletContext.removeAttribute("counter");
?
5 實際應用
① 獲取web應用的初始化參數
1 <!-- 所有servlet都可以訪問 --> 2 <context-param> 3 <param-name>name</param-name> 4 <param-value>latinyTest3</param-value> 5 </context-param>
6 //獲取: 7 ServletContext serCon = this.getServletContext(); 8 String name = serCon.getInitParameter("name"); 9
10 //如果文件在src下,應該使用類加載器讀取 11 InputStream 12 inpStr2= ContextTest5.class.getClassLoader().getResourceAsStream("dbinfo.properties");
?
② 跳轉頁面技術
//1 response.sendRedirect("/web應用名/資源名"); //2 request.getRequestDispatcher("/資源名").forward(request, response); //3 this.getServletContext().getRequestDispatcher("/url").forward(request, response);
?
③ 讀取資源文件
//a 創建資源文件,dbinfo.properties username=latiny password=123456abc age=28 sex=male
//b讀取資源文件 ServletContext serCon = this.getServletContext(); //1 首先讀取到文件 InputStream inpStr = serCon.getResourceAsStream("dbinfo.properties"); //2 創建Properties,然后loadinStr到Properties對象里 Properties proper= new Properties(); proper.load(inpStr);//根據Properties對象的key獲取value String name=proper.getProperty("username"); String password=proper.getProperty("password");
④ 獲取文件全路徑
ServletContext serCon = this.getServletContext(); //讀取到文件全路徑 String path = serCon.getRealPath("/images/2.png"); String path = serCon.getRealPath("2.png");
?
⑤ web網站實際應用
網站計數器;網站在線用戶顯示;簡單聊天系統;
如果涉及到不同用戶共享數據,并且這些數據量不大,同時又不希望寫入到數據庫中,則可以考慮ServletContext實現;
?
實現網站計數器功能時,用戶每刷新一次會自動增加一次訪問記錄,如何避免表單重復提交:
使用sendRedirect 訪問即可:
response.sendRedirect("/UserManager4/MainFrame");
?
⑥ 使用ServletContext注意事項
ServletContext會長時間保存在服務器內存中,因此建議不要想ServletContext中添加過大的數據。
?
轉載于:https://www.cnblogs.com/Latiny/p/8458539.html
總結
以上是生活随笔為你收集整理的8 ServletContext的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “草拆花心开”上一句是什么
- 下一篇: 留学要多少钱啊?