@WebListener
public class MyAttributeListener implements ServletContextAttributeListener,
HttpSessionAttributeListener, ServletRequestAttributeListener {
public void attributeAdded(ServletContextAttributeEvent sae) {
String name = sae.getName();
System.out.println("an attribute has been added to the ServletContext:" + name + "="
+ sae.getServletContext().getAttribute(name));
}
public void attributeRemoved(ServletContextAttributeEvent sae) {
String name = sae.getName();
System.out.println("an attribute has been removed from the ServletContext:" + name);
}
public void attributeReplaced(ServletContextAttributeEvent sae) {
String name = sae.getName();
System.out.println("an attribute has been replaced in the ServletContext:" + name + "="
+ sae.getServletContext().getAttribute(name));
}
public void attributeAdded(HttpSessionBindingEvent hbe) {
String name = hbe.getName();
System.out.println("an attribute has been added to a session:" + name + "="
+ hbe.getSession().getAttribute(name));
}
public void attributeRemoved(HttpSessionBindingEvent hbe) {
String name = hbe.getName();
System.out.println("an attribute has been removed from a session:" + name);
}
public void attributeReplaced(HttpSessionBindingEvent hbe) {
String name = hbe.getName();
System.out.println("an attribute has been replaced in a session:" + name + "="
+ hbe.getSession().getAttribute(name));
}
public void attributeAdded(ServletRequestAttributeEvent sra) {
String name = sra.getName();
System.out.println("an attribute has been added to the ServletRequest:" + name + "="
+ sra.getServletRequest().getAttribute(name));
}
public void attributeRemoved(ServletRequestAttributeEvent sra) {
String name = sra.getName();
System.out.println("an attribute has been removed from the ServletRequest:" + name);
}
public void attributeReplaced(ServletRequestAttributeEvent sra) {
String name = sra.getName();
System.out.println("an attribute has been replaced on the ServletRequest:" + name + "="
+ sra.getServletRequest().getAttribute(name));
}
}
启动Tomcat,测试
a ServletRequest is about to come into scope of the web application.
an attribute has been replaced on the ServletRequest:org.apache.catalina.ASYNC_SUPPORTED=false
a session has been created.
an attribute has been added to the ServletContext:username=itcast
an attribute has been replaced in the ServletContext:username=itheima
an attribute has been removed from the ServletContext:username
an attribute has been added to a session:username=itcast
an attribute has been replaced in a session:username=itheima
an attribute has been removed from a session:username
an attribute has been added to the ServletRequest:username=itcast
an attribute has been replaced on the ServletRequest:username=itheima
an attribute has been removed from the ServletRequest:username
a ServletRequest is about to go out of scope of the web application.