如何在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后,您将收到以下结果:
欢迎访问我的网站
会话信息
| 会话信息 | 值 |
|---|---|
| ID | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
| 创建时间 | 2010年6月8日星期二 17:26:40 GMT+04:00 |
| 上次访问时间 | 2010年6月8日星期二 17:26:40 GMT+04:00 |
| 用户ID | ABCD |
| 访问次数 | 0 |
现在尝试第二次运行相同的JSP,您将收到以下结果。
欢迎再次访问我的网站
会话信息
| 信息类型 | 值 |
|---|---|
| ID | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
| 创建时间 | 2010年6月8日星期二 17:26:40 GMT+04:00 |
| 上次访问时间 | 2010年6月8日星期二 17:26:40 GMT+04:00 |
| 用户ID | ABCD |
| 访问次数 | 1 |
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP