日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

页面访问次数的统计

發布時間:2024/6/21 39 生活家
生活随笔 收集整理的這篇文章主要介紹了 页面访问次数的统计 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  有時候我們需要統計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>

  訪問結果:

      

總結

以上是生活随笔為你收集整理的页面访问次数的统计的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。