用ServletContext保存页面的访问统计
我们知道一个Web应用程序只有一个ServletContext对象,而且该对象可以被Web应用程序中的所有Servlet所访问,因此使用ServletContext对象来保存一些需要在Web应用程序中共享的信息是再合适不过了。要在ServletContext对象中保存共享信息,可以调用该对象的setAttribute()方法,要获取共享信息,可以调用该对象的getAttribute()方法。针对本例,我们可以调用setAttribute()方法将访问计数保存到上下文对象中,新增一次访问时,调用getAttribute()方法从上下文对象中取出访问计数加1,然后再调用setAttribute()方法保存回上下文对象中。import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CounterServlet extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = getServletContext(); Integer count = null; synchronized(context) { count = (Integer) context.getAttribute("counter"); if (null == count) { count = new Integer(1); } else { count = new Integer(count.intValue() + 1); } context.setAttribute("counter", count); } resp.setContentType("text/html;charset=gb2312"); PrintWriter out = resp.getWriter(); out.println("<html><head>"); out.println("<title>页面访问统计</title>"); out.println("</head><body>"); out.println("该页面已被访问了" + "<b>" + count + "</b>" + "次"); out.println("</body></html>"); out.close(); } }另外还需要注意的是,访问次数在重启Tomcat服务器后,将重新从1开始,为了永久保存访问次数,可以将这个值保存到文件或数据库中。
页:
[1]