Session域监听器
一、Session域共有四个监听器接口
HttpSessionListener HttpSessionAttributeListener HttpSessionBindingListener HttpSessionActivationListener
接下来我们就认识一些每个接口和接口中每个方法的用处
二、监听器代码
HttpSessionListener HttpSessionAttributeListener
代码语言:javascript复制package com.lanson.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* @Author: Lansonli
* @Description: MircoMessage:Mark_7001
*/
@WebListener
public class MySessionListener implements HttpSessionListener , HttpSessionAttributeListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("任何一个Session对象创建");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("任何一个Session对象的销毁");
}
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("任何一个Session对象中添加了数据");
}
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("任何一个Session对象中移除了数据");
}
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
System.out.println("任何一个Session对象中修改了数据");
}
}
HttpSessionBindingListener
package com.lanson.listener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
/**
* @Author: Lansonli
* @Description: MircoMessage:Mark_7001
*/
/*
* 可以监听具体的某个session对象的事件的
*
* HttpSessionListener 只要在web.xml中配置或者通过@WebListener注解就可以注册监听所有的Session对象
* HttpSessionBindingListener 必须要通过setAttribute方法和某个session对象绑定之后,监听单独的某个Session对象
* */
public class MySessionBindingListener implements HttpSessionBindingListener {
// 绑定方法
/*
session.setAttribute("mySessionBindingListener",new MySessionBindingListener())
*/
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("监听器和某个session对象绑定了");
}
// 解除绑定方法
/*
* 当发生如下情况,会触发该方法的运行
* 1 session.invalidate(); 让session不可用
* 2 session到达最大不活动时间,session对象回收 ;
* 3 session.removeAttribute("mySessionBindingListener");手动解除绑定
* */
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
}
}
HttpSessionActivationListener
代码语言:javascript复制package com.lanson.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
/**
* @Author: Lansonli
* @Description: MircoMessage:Mark_7001
*/
public class MySessionActivationListener implements HttpSessionActivationListener {
@Override
public void sessionWillPassivate(HttpSessionEvent se) {
System.out.println("session即将钝化");
}
@Override
public void sessionDidActivate(HttpSessionEvent se) {
System.out.println("session活化完毕");
}
}