如何在JSP頁面中使用session跟蹤網頁的訪問時間?


此示例描述如何使用HttpSession物件查詢會話的建立時間和上次訪問時間。如果不存在會話,我們將為請求關聯一個新的會話。

示例

 線上演示

<%@ page import = "java.io.*,java.util.*" %>
<%
   // Get session creation time.
   Date createTime = new Date(session.getCreationTime());

   // Get last access time of this Webpage.
   Date lastAccessTime = new Date(session.getLastAccessedTime());

   String title = "Welcome Back to my website";
   Integer visitCount = new Integer(0);
   String visitCountKey = new String("visitCount");
   String userIDKey = new String("userID");
   String userID = new String("ABCD");

   // Check if this is new comer on your Webpage.
   if (session.isNew() ) {
      title = "Welcome to my website";
      session.setAttribute(userIDKey, userID);
      session.setAttribute(visitCountKey, visitCount);
   }
   visitCount = (Integer)session.getAttribute(visitCountKey);
   visitCount = visitCount + 1;
   userID = (String)session.getAttribute(userIDKey);
   session.setAttribute(visitCountKey, visitCount);
%>
<html>
   <head>
      <title>Session Tracking</title>
   </head>
   <body>
      <center>
         <h1>Session Tracking</h1>
      </center>
      <table border = "1" align = "center">
         <tr bgcolor = "#949494">
            <th>Session info</th>
            <th>Value</th>
         </tr>
         <tr>
            <td>id</td>
            <td><% out.print( session.getId()); %></td>
         </tr>
         <tr>
            <td>Creation Time</td>
            <td><% out.print(createTime); %></td>
         </tr>
         <tr>
            <td>Time of Last Access</td>
            <td><% out.print(lastAccessTime); %></td>
         </tr>
         <tr>
            <td>User ID</td>
            <td><% out.print(userID); %></td>
         </tr>
         <tr>
            <td>Number of visits</td>
            <td><% out.print(visitCount); %></td>
         </tr>
      </table>
   </body>
</html>

現在將上述程式碼放入**main.jsp**中,並嘗試訪問**https://:8080/main.jsp**。執行URL後,您將收到以下結果:

歡迎訪問我的網站

會話資訊

會話資訊
ID0AE3EC93FF44E3C525B4351B77ABB2D5
建立時間2010年6月8日星期二 17:26:40 GMT+04:00
上次訪問時間2010年6月8日星期二 17:26:40 GMT+04:00
使用者IDABCD
訪問次數0

現在嘗試第二次執行相同的JSP,您將收到以下結果。

歡迎再次訪問我的網站

會話資訊

資訊型別
ID0AE3EC93FF44E3C525B4351B77ABB2D5
建立時間2010年6月8日星期二 17:26:40 GMT+04:00
上次訪問時間2010年6月8日星期二 17:26:40 GMT+04:00
使用者IDABCD
訪問次數1

更新於:2019-07-30

490 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.