我思故我强

jsp获得在线用户

 
 
用HttpSessionListener 。

package demo.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounter implements HttpSessionListener {
     public void sessionCreated(HttpSessionEvent event) {
         ServletContext ctx = event.getSession( ).getServletContext( );
         Integer numSessions = (Integer) ctx.getAttribute("numSessions");
         if (numSessions == null) {
             numSessions = new Integer(1);
         }
         else {
             int count = numSessions.intValue( );
             numSessions = new Integer(count + 1);
         }
         ctx.setAttribute("numSessions", numSessions);
     }
     public void sessionDestroyed(HttpSessionEvent event) {
         ServletContext ctx = event.getSession( ).getServletContext( );
         Integer numSessions = (Integer) ctx.getAttribute("numSessions");
         if (numSessions == null) {
             numSessions = new Integer(0);
         }
         else {
             int count = numSessions.intValue( );
             numSessions = new Integer(count - 1);
         }
         ctx.setAttribute("numSessions", numSessions);
     }
}

在这个解决方案中,任何一个Session被创建或者销毁时,都会通知SessionCounter 这个类,当然通知的原因是必须在web.xml文件中做相关的配置工作。如下面的配置代码:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd">
    
<web-app>
   <display-name>Struts Examples</display-name>
  
   <listener>
       <listener-class>demo.listener.SessionCounter
       </listener-class>
   </listener>

posted on 2008-07-28 18:51 李云泽 阅读(317) 评论(0)  编辑  收藏 所属分类: J2EE


只有注册用户登录后才能发表评论。


网站导航: