页面访问次数的统计

  有时候我们需要统计Web站点上的一个特定页面的访问次数,要完成这个功能,我们可以使用ServletContext对象来保存访问的次数。我们知道一个Web应用程序只有一个ServletContext对象,而且该对象可以被Web应用程序中的所有Servlet所访问,因此使用ServletContext对象来保存一些需要在Web应用程序中共享的信息是再合适不过了。

  要在ServletContext对象中保存共享信息,可以调用该对象的setAttribute()方法,要获取共享信息,可以调用该对象的getAttribute()方法。我们可以调用setAttribute()方法将访问计数保存到上下文对象中,新增一次访问时,调用getAttribute()方法从上下文对象中取出访问计数加1,然后再调用setAttribute()方法保存回上下文对象中。

  Servlet代码如下:

    package com.tz.jsd1412.day02.servlet;

    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 CountServlet extends HttpServlet{

        @Override
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException
        {
            ServletContext context = getServletContext();
            Integer count = null;
        
            synchronized (context) {
                count = (Integer) context.getAttribute("count");
                if (count == null) {
                    count = new Integer(1);
                }else{
                    count = new Integer(count.intValue() + 1);
                }
                context.setAttribute("count", count);
        }
            
            PrintWriter out = resp.getWriter();
        
            out.print("<html><head>");
            out.print("<title>页面访问统计</title>");
            out.print("<head><body>");
            out.print("该页面已被访问了"+"<br>"+count+"<br>"+"次");
            out.print("</body></html>");
        
            out.close();
        }
    }
  

  web.xml配置如下:

     <!-- 配置servlet -->
      <servlet>
          <!-- servlet的名字 -->
          <servlet-name>CountServlet</servlet-name>
          <!-- Servlet的权限定名 -->
          <servlet-class>com.tz.jsd1412.day02.servlet.CountServlet</servlet-class>
      </servlet>
 
      <!-- servlet的映射 -->
      <servlet-mapping>
          <!-- servlet的名字,一定要和对应的Servet名字相同 -->
          <servlet-name>CountServlet</servlet-name>
          <!-- url地址 -->
          <url-pattern>/day02/count</url-pattern>
      </servlet-mapping>

   访问结果:

      

posted @   金鱼的第七秒记忆  阅读(1320)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示