**监听器Listener
** Servlet监听器是Servlet规范中定义的一种特殊类,用于监听ServletContext、HttpSession和ServletRequest等域对象的创建与销毁事件,以及监听这些域对象中属性发生修改的事件。
监听对象
1、ServletContext:application(整个应用只存在一个)
2、HttpSession:session(针对每一个对话)
3、ServletRequest:request(针对每一个客户请求)
listener小栗子
package com.srzx.sms.listener;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener()
public class OnlineListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
String name = se.getName();
//登录用户的session发生变化
if("account".equals(name)){
ServletContext application = se.getSession().getServletContext();
int online_num = application.getAttribute("online_num") == null ? 0 : (Integer) application.getAttribute("online_num");
System.out.println("online_num = " + online_num);
online_num++;
application.setAttribute("online_num",online_num);
}
String value = (String) se.getValue();
System.out.println("OnlineListener.attributeAdded");
}
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
String name = se.getName();
//退出用户的session发生变化
if("account".equals(name)){
ServletContext application = se.getSession().getServletContext();
int online_num = application.getAttribute("online_num") == null ? 0 : (Integer) application.getAttribute("online_num");
System.out.println("online_num = " + online_num);
online_num--;
application.setAttribute("online_num",online_num);
}
}
}