ServletContext容器,網站訪問量
阿新 • • 發佈:2019-01-09
ServletContext代表當前整個web專案,是一個比較大的專案容器;
public class ServletContextDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>" );
out.println(" <BODY>");
//拿到ServletContext容器
ServletContext context = getServletContext();
//物件強轉,Object強轉為Integer,如果原來沒有這個屬性,則獲得的物件為null
Integer count = (Integer) context.getAttribute("count");
if(count==null){
count=1;
}else {
count++;
}
getServletContext().setAttribute("count", count);
out.print("網站訪問量:"+getServletContext().getAttribute("count"));
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}