यह उदाहरण दर्शाता है कि सेशन के निर्माण समय और अंतिम-एक्सेस समय का पता लगाने के लिए HttpSession ऑब्जेक्ट का उपयोग कैसे करें। यदि कोई सेशन पहले से मौजूद नहीं है तो हम अनुरोध के साथ एक नया सेशन जोड़ देंगे।
<%@ 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 = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // जांचें कि क्या यह आपके वेबपेज पर नया विज़िटर है। 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 चलाते हैं, तो आपको निम्न परिणाम प्राप्त होगा -
Welcome to my website
Session Information
| Session info | value |
|---|---|
| id | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
| Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
| Time of Last Access | Tue Jun 08 17:26:40 GMT+04:00 2010 |
| User ID | ABCD |
| Number of visits | 0 |