【jsp網站計數功能】 application session

來源:互聯網
上載者:User

標籤:style   blog   io   color   使用   java   sp   檔案   div   

在jsp頁面中實現網站計數器的方法有很多,其中比較普遍的做法是利用application 和session對象。application對象可被所有使用者共用;session是單使用者共用,使用者從訪問系統開始到退出系統,都可以使用session。網站計數器的實現思路是:當系統建立一個session對象時,將application中儲存的計數變數加1

 

count.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>  </head>    <body>    <%!        synchronized void countPeople(){            ServletContext application = this.getServletContext();            Integer number = (Integer) application.getAttribute("count");            if(number == null){                number = new Integer(1);                application.setAttribute("count", number);            }            else{                number = new Integer(number.intValue() + 1);                application.setAttribute("count",number);            }        }     %>          <%          if(session.isNew()){             countPeople();         }         Integer yourNumber = (Integer) application.getAttribute("count");     %>     <p></p>     歡迎訪問本網站,您是第<%= yourNumber %>個訪問使用者。  </body></html>

 

在上述代碼中,為了避免使用application 對象出現並發問題,因此使用了synchronized 關鍵字。為了避免頁面重新整理問題,添加了session.isNew()判斷,如果session對象是建立的,表明使用者開始訪問系統,將計數器加1;當使用者重新整理當前頁面時,由於session對象不是建立的,因此避免了重複加1的問題

 

實際上,在實現計數器功能是,需要注意一些細節問題,例如頻繁重新整理和並發訪問等。由於application對象的生命週期與伺服器啟動和停止相關,因此如果伺服器由於出現問題重啟,application儲存的計數器將清空。要解決該問題可以將計數器的值儲存在檔案中,利用讀寫檔案的功能再對計數器加1.

【jsp網站計數功能】 application session

聯繫我們

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