监听器是用来监听你的web应用,监听许多信息的初始化、销毁、增加、修改、删除等等
一、对监听器的划分
1、按监听的对象划分,监听器可以分为:ServletContext对象监听器、HttpSession对象监听器、ServletRequest对象监听器。
2、安监听的事件划分,监听器可以分为:对象自身的创建和销毁的监听器、对象中属性的创建和消除的监听器、session中的某个对象的状态变化的监听器。
二、创建监听器的步骤
1、注册监听器
#通过注解的方式注册监听器 @WebListener #在web.xml中注册监听器com.mrlang.listener.MyContextListener
2、上下文监听ServletContext、Session监听、session中属性监听
//上下文监听ServletContext
public class MyContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//获取到上下文对象
ServletContext application = servletContextEvent.getServletContext();
System.out.println("上下文初始化"+application);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("上下文销毁");
}
}
//session监听
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("session创建"+httpSessionEvent.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("session销毁"+httpSessionEvent.getSession());
}
}
//session中属性监听
public class MySessionAttributeListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("session属性添加:"+httpSessionBindingEvent.getName());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("session属性移除:"+httpSessionBindingEvent.getName());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("session属性替换:"+httpSessionBindingEvent.getName());
}
}
三、监听器的应用
在线人数的统计:
1、先获取容器中的数量计数器,如果没有,创建后存进去
2、每创建一个session,计数器加1
3、每销毁一个session,计数器减1
//应用程序、网站监听器:统计在线人数
@WebListener
public class OnlineListener implements ServletContextListener, HttpSessionListener {
ServletContext appliction;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//获取上下文对象
appliction = servletContextEvent.getServletContext();
//是否有计数器
if(appliction.getAttribute("count")==null){
//存进去,只执行一次
appliction.setAttribute("count",0);
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
//获取原来的计数器的值
Integer count=Integer.valueOf(appliction.getAttribute("count").toString());
count++;
//存进去
appliction.setAttribute("count",count);
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
Integer count=Integer.valueOf(appliction.getAttribute("count").toString());
count--;
appliction.setAttribute("count",count);
}
}



