JSP簡單練習-網站計數器

來源:互聯網
上載者:User

標籤:網站計數器

<%@ page contentType="text/html;charset=gb2312" %><%@ page import="javax.servlet.*" %><html><head><title>網站計數器</title></head><body>   <%!      synchronized void countPeople()      {  // 序列化計數函數         ServletContext application=((HttpServlet)(this)).getServletContext();         Integer number=(Integer)application.getAttribute("Count");         if(number==null)         {  // 如果是第1個訪問本站            number=new Integer(1);            application.setAttribute("Count", number);         }         else         {            number=new Integer(number.intValue()+1);            application.setAttribute("Count",number);         }      }   %>   <%      if(session.isNew())      {  // 如果是一個新的會話         out.println("是一個新會話!");         countPeople();      }      Integer yourNumber=(Integer)application.getAttribute("Count");      out.println(yourNumber);   %>   <p>歡迎訪問本站,你是第      <%=yourNumber %>           個訪問使用者。</body></html>

程式利用synchronize關鍵字對計數函數進行了序列化(有的書中叫序列化),以確保當兩個用戶端同時訪問網頁而修改計數值時不會產生衝突;getServletContext()方法來得到application對象,因為有些Web伺服器並不直接支援application對象,必須先得到其上下文;如果還是第一個訪問的客戶,則前面代碼中得到的number會是空值,故置初始值為1,否則做增1處理;如果是一個新的會話則調用計數函數,得到計數值並將其顯示。

可以發現,當重新整理頁面時,其數值並不會增加,只有關閉了本網站的所有視窗再重新訪問時,才會增1,因為這又是一個新的會話。


JSP簡單練習-網站計數器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.