ใช้ HttpSession object ติดตามเวลาสร้าง (creation time) และเวลาเข้าถึงล่าสุด (last accessed time)
ตัวอย่าง main.jsp
<%@ page import="java.io.*,java.util.*" %>
<%
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = 0;
String visitCountKey = "visitCount";
String userIDKey = "userID";
String userID = "ABCD";
if (session.isNew()) {
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer) session.getAttribute(visitCountKey);
visitCount++;
userID = (String) session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head><title>Session Tracking</title></head>
<body>
<center><h1><%= title %></h1></center>
<table border="1" align="center">
<tr bgcolor="#949494"><th>Session Info</th><th>Value</th></tr>
<tr><td>ID</td><td><%= session.getId() %></td></tr>
<tr><td>Creation Time</td><td><%= createTime %></td></tr>
<tr><td>Last Access Time</td><td><%= lastAccessTime %></td></tr>
<tr><td>User ID</td><td><%= userID %></td></tr>
<tr><td>Visit Count</td><td><%= visitCount %></td></tr>
</table>
</body>
</html>
ผลลัพธ์ครั้งแรก (New Session)
| Session Info | Value |
| ID | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
| Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
| Last Access Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
| User ID | ABCD |
| Visit Count | 0 |
ผลลัพธ์ครั้งที่ 2 (Existing Session)
| Session Info | Value |
| ID | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
| Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
| Last Access Time | Tue Jun 08 17:27:15 GMT+04:00 2010 |
| User ID | ABCD |
| Visit Count | 1 |
เมธอด HttpSession สำคัญ
| เมธอด | คำอธิบาย |
getId() | Session ID |
getCreationTime() | เวลาสร้าง (milliseconds since epoch) |
getLastAccessedTime() | เวลาเข้าถึงล่าสุด |
setMaxInactiveInterval(sec) | ตั้ง timeout |
getMaxInactiveInterval() | อ่าน timeout (วินาที) |
invalidate() | ยกเลิก session |
isNew() | session ใหม่หรือไม่ |