监听器的编写步骤:
a.编写一个监听器类去实现监听器接口b.覆盖监听器的方法
c.需要在web.xml中进行配置---注册
MyHttpSessionListener.java(自定义的监听器,实现HttpSessionListener):
package com.xxx.demo;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MyHttpSessionListener implements HttpSessionListener{
@Override
// 监听session对象的创建。 每个客户端的会话建立时触发
public void sessionCreated(HttpSessionEvent se) {
System.out.println("session创建:"+se.getSession().getId());
// 可以实现记录访问用户数量的需求
// jsp页面的 <%@ page session="true" %>; 第一次访问jsp页面就会自动创建session
}
@Override
// 监听session对象的销毁。 会话过期、手动失效、宕机时触发
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("session销毁");
}
}
web.xml(配置文件, 注册自定义的监听器):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>MyWeb</display-name>
<!-- 注册监听器(相当于hook钩子) -->
<listener>
<listener-class>com.xxx.demo.MyHttpSessionListener</listener-class> <!-- 必须是全名 (反射实现) -->
</listener>
</web-app>