监听器主要针对三个对象
- ServletContext
- HttpSession
- ServletRequest
使用方式
- 创建*Listener接口的实现类
- 在web.xml中注册该类
在同时注册多个同接口的监听器时,执行顺序参照web.xml中的注册顺序
- 监听器监听类型
- 对象的创建和销毁
- 对象属性的添加、替换、移除
创建实现类
// 用于监听session创建和销毁的监听器
package listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
// 获取本次事件创建session的id
String sessionId = httpSessionEvent.getSession().getId();
System.out.println("create session that id = " + sessionId);
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
// 删除session的id
String sessionId = httpSessionEvent.getSession().getId();
System.out.println("session has been destroy that id = " + sessionId);
}
}
在web.xml中注册
Archetype Created Web Application index.jsp listener.SessionListener
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



