HttpSessionListener的用法和实例

HttpSessionListener:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
Session创建和销毁的时候可以监听到。



例 2.2.3.1

package com;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MyHttpSessionListener implements
HttpSessionListener {
    public void sessionCreated(javax.servlet.http.HttpSessionEvent arg0) {
        System.out.println("马克-to-win session Initialized"+arg0.getSession().getId());
    }
    public void sessionDestroyed(javax.servlet.http.HttpSessionEvent arg0) {
        System.out.println("马克-to-win destroyed"+arg0.getSession().getId());
    }
}



web.xml加入下面这段话:

  <listener>
    <listener-class>com.MyHttpSessionListener</listener-class>
  </listener>




用下面这个servlet测试:


package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ServletHello2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         System.out.println("before session create");
         HttpSession hs=request.getSession();
         System.out.println("after session create");
         hs.invalidate();
         System.out.println("after session invalidate");
    }
}



运行这个servlet以后,console里的输出结果是:

before session create
马克-to-win session InitializedAD8FE2BD460813E320F8DE859DF6D631
after session create
马克-to-win destroyedAD8FE2BD460813E320F8DE859DF6D631
after session invalidate