监听器简介
监听器主要用来监听ServletContext,HttpSession,ServletRequst的创建和销毁,是一个实现特定接口的普通Java类。在某些动作前后增加处理,实现监控,例如统计在线人数
监听器的三类八种
session监听器代码
//监听器实现监听Session的生命周期,session的创建和销毁
//当有新的session对象被创建时就会被调用
@WebListener
public class listener01 implements HttpSessionListener{
@override
public void sessionCreated(HttpSessionEvent httpSession){
}
//当有session被销毁时就会调用
@override
public void sessionDetroyed(HttpSessionEvent httpSessionEvent){
}
}
创建一个session对象,该对象被监听
@WebServlet(“/ser03”)//ser03是在网址中输入的尾巴
public class Servlet03 extends HttpServlet{
@Override
protected void service(HttpServletRequest reg, HttpServletResponse resp) throwsServletException, IException{
//获取并创建session对象
HttpSession session = req.getSession();
}
}
ServletContextAttributeListener接口
•实现该接口的程序,能够监听ServletContext属性的变化,例如:当往ServletContext中添加数时,该程序会被调用
•ServletContextAttributeEvent的主要方法
–getName()
–getValue()
•attributeReplaced()方法中,getName()与getValue()是取之前的值
HttpSessionListener
•HttpSessionListener监听Session对象的创建与销毁,当有Session对象产生或销毁时,会自动调用sessionCreated()或sessionDestroyed()两个方法
HttpSessionListener接口与HttpSessionActivationListener接口都使用HttpSessionEvent事件对象
•HttpSessionEvent类主要的方法:
–getSession()
•HttpSessionAttributeListener会监听Session属性的变化,功能与ServletContextAttributeListener接口类似,包含三个方法
–attributeAdded()
–attributeReplaced()
–attributeRemove()
HttpSessionBindingEvent事件
•HttpSessionBindingEvent事件主要有三个方法
–getName()
–getSession()
–getValue()
HttpSessionActivationListener接口
•该接口主要用于:同一个Session转移到不同JVM的情形(如:负载均衡,这些JVM可以在同一台机器或分散在网络中的多台机器)
•当Session被储存起来,并且等待转移至另一个JVM,这段时间称为失效状态(Passivate),若Session中的属性对象实现HttpSessionActivationListener接口时,Container会自动调用sessionWillPassivate()方法通知该对象的Session已变成失效状态
•当Session被转移至其他JVM之后,它又成为有效状态(Activate),此时Container会自动调用sessionDidActivate()方法通知该对象的Session已变成有效状态