日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

页面访问次数的统计

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

  有時候我們需要統(tǒng)計Web站點(diǎn)上的一個特定頁面的訪問次數(shù),要完成這個功能,我們可以使用ServletContext對象來保存訪問的次數(shù)。我們知道一個Web應(yīng)用程序只有一個ServletContext對象,而且該對象可以被Web應(yīng)用程序中的所有Servlet所訪問,因此使用ServletContext對象來保存一些需要在Web應(yīng)用程序中共享的信息是再合適不過了。

  要在ServletContext對象中保存共享信息,可以調(diào)用該對象的setAttribute()方法,要獲取共享信息,可以調(diào)用該對象的getAttribute()方法。我們可以調(diào)用setAttribute()方法將訪問計數(shù)保存到上下文對象中,新增一次訪問時,調(diào)用getAttribute()方法從上下文對象中取出訪問計數(shù)加1,然后再調(diào)用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>頁面訪問統(tǒng)計</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的權(quán)限定名 -->
    <servlet-class>com.tz.jsd1412.day02.servlet.CountServlet</servlet-class>
    </servlet>

    <!-- servlet的映射 -->
    <servlet-mapping>
     <!-- servlet的名字,一定要和對應(yīng)的Servet名字相同 -->
     <servlet-name>CountServlet</servlet-name>
     <!-- url地址 -->
     <url-pattern>/day02/count</url-pattern>
    </servlet-mapping>

  訪問結(jié)果:

      

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。