jsp中有没有类似asp.net和asp中Session_Start的方法。我想要在每次启动一个新会话时执行一个动做,怎么办呀

解决方案 »

  1.   

    也经解决了,用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>