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