이 예제에서는 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://localhost: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 |