Listener的两类监听对象:
1、HttpSessionListener
可以监控session的创建或销毁,进入动态页面jsp会创建session,监听结果:
如果将jsp页面session属性改为false,将不会创建。
2、HTTPSessionAttributeListener
当session的属性发生改变时可以检测到。
例如:获得在线人数,编写HttpSessionAttributeListener类,编写jsp,配置web文件即可:
TestHttpSessionAttributeListener类:
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("TestHttpSessionAttributeListener-->>attributeAdded()");
System.out.println("name=======" + se.getName());
System.out.println("value========" + se.getValue());
if("user_info".equals(se.getName())){
Integer count = (Integer)se.getSession().getServletContext().getAttribute("count");
if(count == null){
count = 1;
}else{
count++;
}
se.getSession().getServletContext().setAttribute("count", count);
}
}
然后再web.xml中配置listener类就可以了:
<listener>
<listener-class>com.orcl.drp.util.listener.TestHttpSessionAttributeListener</listener-class>
</listener>
监听结果:
总结:
监听器在java web项目中经常用到,今天来总结一下,请多指教!
感谢您的阅读!