一個簡單的網站計數器

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   使用   io   資料   

 在做網站的時候,經常需要統計有多少人訪問過本網站,統計人數應當根據是否是一個新的回話來判斷是否是一個新訪問網站的使用者.application對象就可以儲存訪問人數.

 關於application對象:application對象用來在多個程式或者多個使用者之間共用資料,使用者使用的application對象都是一樣的.這與session不同.伺服器一旦啟動,就會自動建立application對象,並一直儲存下去,直到伺服器關閉,application對象自動消失.下面就是利用application對象實現一個網站計數器,代碼如下:

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4   <body> 5       <%! 6         synchronized void count(){      //使用sychronized關鍵字對該函數進行序列化, 7                                         //確保當兩個使用者同時訪問網頁而修改計數值時不會有衝突. 8             ServletContext application = ((HttpServlet)(this)).getServletContext(); 9             Integer count = (Integer)application.getAttribute("count");10             11             if(count==null){12                 count = new Integer(1);13                 application.setAttribute("count",count);14             }else{15                 count = new Integer(count.intValue()+1);16                 application.setAttribute("count",count);17             }18         }      19       %>20       21       <%22           if(session.isNew()){        //判斷是否為一個新的回話.23               count();24               out.println("你是第"+application.getAttribute("count")+"個訪問本網站");25           }26       %>27   </body>28 </html>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.