什么是监听器?
1、Filter 过滤器它是 JavaWeb 的三大组件之一。
2、Web监听器是Servlet规范中定义的一种特殊类。
- 用于监听
ServletContext
、HttpSession
和ServletRequest
等域对象的创建与销毁事件。 - 用于监听域对象的属性发生修改的事件
- 可以在事件发生前、发生后做一些必要的处理
对WEB中的操作进行监听(在web中可以对application、session和request三种操作进行监听)
@WebListener
监听application的属性
创建监听类
public class ListenerAbttriDemo implements ServletContextAttributeListener {
public void attributeAdded(ServletContextAttributeEvent arg0) {
System.out.println("增加属性:"+arg0.getName()+"="+arg0.getValue());
//System.out.println("增加属性:");
}
public void attributeRemoved(ServletContextAttributeEvent arg0) {
System.out.println("删除属性:"+arg0.getName()+"="+arg0.getValue());
}
public void attributeReplaced(ServletContextAttributeEvent arg0) {
System.out.println("修改属性:"+arg0.getName()+"="+arg0.getValue());
}
}
注册:
<listener>
<listener-class>cn.web.listener.ListenerAbttriDemo</listener-class>
</listener>
修改增加、修改和删除属性的操作:
<%
this.getServletContext().setAttribute("name","haoren");
this.getServletContext().setAttribute("name","haoren");
this.getServletContext().removeAttribute("name");
%>
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener (不用注册)
对request的监听
ServletRequestAttributeListener
Web.xml的书写的顺序:过滤器、监听器、servlet