1. 程式人生 > >Servlet------ServletContext介面

Servlet------ServletContext介面

一、執行在Java虛擬機器中的每一個Web應用程式都只有一個與之相關的Servlet上下文,用ServletContext介面來表示,ServletContext物件可以被Web應用程式中的所有Servlet所訪問,因此可以用此物件來儲存一些需要在Web應用程式中共享的資訊

二、頁面訪問量統計例項

public class CounterServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)  throws ServletException, IOException{

ServletContext context = getServletContext();
-----Servlet容器在Servlet例項化期間向其傳遞ServletConfig物件,通過ServletConfig物件的getServletContext();方法得到ServletContext物件

Integer count = null;

synchronized(context){
-----同步塊

count = (Integer)context.getAttribute("counter");
-----獲取ServletContext物件中屬性名為counter屬性的值,若無則返回空

if(null == count){

count = new Integer(1);

}

else{

count = new Integer(count.intValue()+1);

}

context.setAttribute("counter",count);
-----將ServletContext物件中屬性名為counter的屬性值設為count,若無則新增

}

res.setContentType("text/html;charset=gb2312");

PrintWriter out = res.getWriter();

out.println("<html><head>");

out.println("<title>頁面訪問統計</title>");

out.println("</head><body>");

out.println("該頁面已被訪問了"+"<b>"+count+"</b>"+"次");

out.println("</body></html>");

out.close();

}

}