基本思想:后台计数setAttribute,前台显示次数getAttribute。
基本步骤:
1) 重写init方法,使得每一次访问该网站的时候,都会调用该方法,并且采用setAttribute(“存入的变量名(count)”,给这个变量存的值)方法,对计数的对象进行初始化为0.
2) 获取计数的count变量,并设置它自增。
3) 向页面输出值,输出统计次数。
public void init() throws ServletException {
getServletContext().setAttribute("count", 0);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
//1)获取ServletContext对象。
ServletContext context=getServletContext();
//2)获取计数对象。
Integer count=(Integer)context.getAttribute("count");
//3) 将计数结果存储到域对象中,并显示到页面上。
context.setAttribute("count", ++count);
response.setHeader("content-type", "text/html;charset=UTF-8");
response.getWriter().write("<h3>该网站一共访问了"+count+"次</h3>");
}