概念
ServletContext是servlet的三大域對象的應用之一(servlet的三大域對象應用為:request、session、application(ServletContext))
Cookie對象存于使用者的用戶端,Session對象每個用戶端有一個存于伺服器端,ServletContext對象存于伺服器端,可被所有用戶端共享。是以當涉及多個使用者共享資訊,而資訊量又不大不想存到資料庫的時候,可以考慮使用ServletContext對象
常見應用
1、網頁計數器
2、顯示多少人同時線上
3、簡單的聊天室功能
ServletContext的特點
1、Web應用伺服器會為在其中的每一個Web應用生成一個ServletContext對象,該ServletContext對象代表該Web應用,并且為該Web應用的所有用戶端所共享。獲得ServletContext對象的引用的常見方法有二,一是
ServletContext context=getServletContext();
二是
ServletContext context=getServletConfig().getServletContext()
2、一個Web應用的所有Servlet對象共用一個ServletContext對象,是以Servlet對象可以通過ServletContext對象進行通信。ServletContext對象又叫做context域對象,簡單的公共聊天室經常用到它。
3、在web應用關閉或reload或者Tomcat關閉時ServletContext會銷毀
舉例說明ServletContext對象的使用
作用:統計網站的通路量
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");//響應正文的MIME類型
response.setCharacterEncoding("UTF-8");//響應的編碼格式
ServletContext context=this.getServletConfig().getServletContext();//獲得ServletContext對象
Integer count=(Integer)context.getAttribute("counter");//從ServletContext對象中獲得計數器對象
if(count==null) {//如果為空,就在ServletContext對象中設定一個計數器的屬性
count=1;
context.setAttribute("counter", count);
}else {
context.setAttribute("counter", count+1);//如果不為空就在該計數器的屬性上加一
}