<% Date createTime = new Date(session.getCreationTime()); Date lastAccessTime = new Date(session.getLastAccessedTime()); " /> JSP的session处理 | 技术教程 | 文章中心 | 北京优胜智连科技有限公司

Article / 文章中心

JSP的session处理

发布时间:2021-12-06 点击数:578

利用JSP内置的session对象的isNew方法判断当前session是否是第一次创建的。使用session.setAttribute来设置属性。

<%@ 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> 

第一次打开该JSP, 看到如下页面:image.png刷新页面,观察到Number of visits的计数器刷新,并且Time of Last Access的值为最后刷新时间:image.png