用JSP的Session实现在线用户统计
假设一个登录用的表单被提交到doLogin.jsp, 表单中包含UserName和password域。节选部分片段:
| <% HttpSessionManager hsm = new HttpSessionManager(application,request,response); try { hsm.login(); } catch ( UserNotFoundException e) { response.sendRedirect("InsufficientPrivilege.jsp?detail=User%20does%20not%20exist."); return; } catch ( InvalidPasswordException e2) { response.sendRedirect("InsufficientPrivilege.jsp?detail=Invalid%20Password"); return; } catch ( Exception e3) { %> Error:<%=e3.toString() %><br> Press <a href="login.jsp">Here</a> to relogin. <% return; } response.sendRedirect("index.jsp"); %> |
再来看看现在我们怎么得到一个当前在线的用户列表。
| <body bgcolor="#FFFFFF"> <table cellspacing="0" cellpadding="0" width="100%"> <tr > <td style="width:24px">SessionId </td> <td style="width:80px" >User </td> <td style="width:80px" >Login Time </td> <td style="width:80px" >Last access Time </td> </tr> <% Vector activeSessions = (Vector) application.getAttribute("activeSessions"); if (activeSessions == null) { activeSessions = new Vector(); application.setAttribute("activeSessions",activeSessions); } Iterator it = activeSessions.iterator(); while (it.hasNext()) { HttpSession sess = (HttpSession)it.next(); JDBCUser sessionUser = (JDBCUser)sess.getAttribute("user"); String userId = (sessionUser!=null)?sessionUser.getUserID():"None"; %> <tr> <td nowrap=''><%= sess.getId() %></td> <td nowrap=''><%= userId %></td> <td nowrap=''> <%= BeaconDate.getInstance( new java.util.Date(sess.getCreationTime())).getDateTimeString()%></td> <td class="<%= stl %>3" nowrap=''> <%= BeaconDate.getInstance( new java.util.Date(sess.getLastAccessedTime())).getDateTimeString()%></td> </tr> <% } %> </table> </body> |
以上的代码从application中取出activeSessions,并且显示出具体的时间。其中BeaconDate类假设为格式化时间的类。
这样,我们得到了一个察看在线用户的列表的框架。

