session内置对象的监听器
和request内置对象的监听一样,可以对session的状态和属性进行监听。
1.对session的状态进行监听
要对状态进行监听需要实现的接口是javax.servlet.http.HttpSessionListener
监听session的状态
package com.xie.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("创建了session"+se.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("销毁了session对象"+se.getSession());
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("访问了servlet方法");
}
配置session内置对象的状态监听器
<!-- 配置session内置对象的状态监听器 -->
<listener>
<listener-class>com.xie.listener.SessionListener</listener-class>
</listener>
以上的代码发现了没有创建session对象,原因是没有在servlet中调用getSession()
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("发送了请求");
req.getSession();
}
此时没有处罚销毁的监听方法,因为session对象还没有销毁
销毁session对象
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().invalidate();
}
以上是对session的状态进行监听,还可以对session的属性进行监听
监听session的属性
要实现session属性的监听需要使用到另外一个接口javax.servlet,http.HttpSessionAttributeListener
监听属性
package com.xie.listener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class SessionAttributeListener implements HttpSessionAttributeListener{
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println("session增加新的属性:"+event.getName()+"="+event.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.out.println("session删除了一个属性:"+event.getName()+"="+event.getValue());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println("session替换了一个属性:"+event.getName()+"="+event.getValue());
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("name", "尼古拉斯");
session.setAttribute("name", "斯巴达");
session.removeAttribute("name");
}
<!-- 配置session内置对象的属性监听器 -->
<listener>
<listener-class>com.xie.listener.SessionAttributeListener</listener-class>
</listener>