需求:你一定见过很多访问量统计的网站,即“你是第XXX个访问本网站的”。因为无论是哪个用户访问指定页面,都会累计访问量。所以这个访问量统计应该是整个项目共享的。很明显需要使用ServletContext来保存访问量。
一个Web项目中所有的资源被访问都要对访问量进行累加。创建一个int类型的变量,用来保存访问量,然后把它保存到SevletContext域中,这样就保证了所有的Servlet都可以访问到它。
(1) 最开始,ServletContext中没有保存访问量相关的属性;
(2) 本站第一次被访问时,创建一个变量设初值为1,保存到SevletContext域中;
(3) 以后再访问本站,就可以从ServletContext中获取这个变量,然后在其基础上加1;
(4) 获取ServletContext对象,查看是否存在名为count的属性,如果存在,说明不是第一次访问;如果不存在,说明是第一次访问:
(4.1) 第一次访问:调用ServletContext的setAttribute()传递一个属性,名为count值为1;
(4.2) 第2~n次访问:调用ServletContext的getAttribute()方法获取访问量count,给count加1,然后调用setAttribute()方法重新赋值。
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext application = this.getServletContext();
Integer count = (Integer) application.getAttribute("count");
if (count == null) {
count = 1;
} else {
count++;
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("<h1>您是第 " + count + " 个访问者</h1>");
application.setAttribute("count", count);
}
}