创建测试页面testattribute.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<title>测试域对象属性变更事件监听器</title>
</head>
<body>
<h3>这是一个测试域对象属性变更事件监听器的页面</h3>
<%
getServletContext().setAttribute("username", "itcast");
getServletContext().setAttribute("username", "itheima");
getServletContext().removeAttribute("username");
session.setAttribute("username", "itcast");
session.setAttribute("username", "itheima");
session.removeAttribute("username");
request.setAttribute("username", "itcast");
request.setAttribute("username", "itheima");
request.removeAttribute("username");
%>
</body>
</html>
创建监听器MyAttributeListener
public class MyAttributeListener implements ServletContextAttributeListener,
HttpSessionAttributeListener, ServletRequestAttributeListener {
public void attributeAdded(ServletContextAttributeEvent sae) {
String name = sae.getName();
System.out.println("ServletContext添加属性:" + name + "="
+ sae.getServletContext().getAttribute(name));
}
public void attributeRemoved(ServletContextAttributeEvent sae) {
String name = sae.getName();
System.out.println("ServletContext移除属性: " + name);
}
public void attributeReplaced(ServletContextAttributeEvent sae) {
String name = sae.getName();
System.out.println("ServletContext替换属性:" + name + "="
+ sae.getServletContext().getAttribute(name));
}
public void attributeAdded(HttpSessionBindingEvent hbe) {
String name = hbe.getName();
System.out.println("HttpSession添加属性:" + name + "="
+ hbe.getSession().getAttribute(name));
}
public void attributeRemoved(HttpSessionBindingEvent hbe) {
String name = hbe.getName();
System.out.println("HttpSession移除属性: " + name);
}
public void attributeReplaced(HttpSessionBindingEvent hbe) {
String name = hbe.getName();
System.out.println("HttpSession替换属性:" + name + "="
+ hbe.getSession().getAttribute(name));
}
public void attributeAdded(ServletRequestAttributeEvent sra) {
String name = sra.getName();
System.out.println("ServletRequest添加属性:" + name + "="
+ sra.getServletRequest().getAttribute(name));
}
public void attributeRemoved(ServletRequestAttributeEvent sra) {
String name = sra.getName();
System.out.println("ServletRequest移除属性: " + name);
}
public void attributeReplaced(ServletRequestAttributeEvent sra) {
String name = sra.getName();
System.out.println("ServletRequest替换属性:" + name + "="
+ sra.getServletRequest().getAttribute(name));
}
}
web.xml中配置监听器
<listener>
<listener-class>
cn.itcast.chapter08.listener.MyAttributeListener
</listener-class>
</listener>
启动Tomcat,测试