JSP的session處理
發(fā)布時(shí)間:2021-12-06 點(diǎn)擊數(shù):688
利用JSP內(nèi)置的session對(duì)象的isNew方法判斷當(dāng)前session是否是第一次創(chuàng)建的。使用session.setAttribute來(lái)設(shè)置屬性。
<%@ 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>
第一次打開(kāi)該JSP, 看到如下頁(yè)面:刷新頁(yè)面,觀察到Number of visits的計(jì)數(shù)器刷新,并且Time of Last Access的值為最后刷新時(shí)間:
上一篇:JSP的session處理 下一篇:JSP和Servlet里的Cookie處理