1、操作域属性的监听器
当对域属性进行增、删、改时,执行的监听器一共有三个:
ServletContextAttributeListener:在ServletContext域进行增、删、改属性时调用下面方法。
public void attributeAdded(ServletContextAttributeEvent evt)
public void attributeRemoved(ServletContextAttributeEvent evt)
public void attributeReplaced(ServletContextAttributeEvent evt)
HttpSessionAttributeListener:在HttpSession域进行增、删、改属性时调用下面方法
public void attributeAdded(HttpSessionBindingEvent evt)
public void attributeRemoved (HttpSessionBindingEvent evt)
public void attributeReplaced (HttpSessionBindingEvent evt)
ServletRequestAttributeListener:在ServletRequest域进行增、删、改属性时调用下面方法
public void attributeAdded(ServletRequestAttributeEvent evt)
public void attributeRemoved (ServletRequestAttributeEvent evt)
public void attributeReplaced (ServletRequestAttributeEvent evt)
下面对这三个监听器的事件对象功能进行介绍:
ServletContextAttributeEvent
String getName():获取当前操作的属性名;
Object getValue():获取当前操作的属性值;
ServletContext getServletContext():获取ServletContext对象。
HttpSessionBindingEvent
String getName():获取当前操作的属性名;
Object getValue():获取当前操作的属性值;
HttpSession getSession():获取当前操作的session对象。
ServletRequestAttributeEvent
String getName():获取当前操作的属性名;
Object getValue():获取当前操作的属性值;
ServletContext getServletContext():获取ServletContext对象;
ServletRequest getServletRequest():获取当前操作的ServletRequest对象。
2、案例
MyServletContextAttributeListener.java
代码语言:javascript复制public class MyServletContextAttributeListener implements ServletContextAttributeListener {
public void attributeAdded(ServletContextAttributeEvent arg0) {
System.out.println("往Context域中添加了一个属性");
System.out.println("属性名是:" arg0.getName());
System.out.println("属性值是:" arg0.getValue());
}
public void attributeRemoved(ServletContextAttributeEvent arg0) {
System.out.println("从Context域中移除了了一个属性");
System.out.println("移除的属性名是:" arg0.getName());
System.out.println("移除的属性值是:" arg0.getValue());
}
public void attributeReplaced(ServletContextAttributeEvent arg0) {
System.out.println("从Context域中替换了一个属性");
System.out.println("替换的属性名是:" arg0.getName());
System.out.println("替换的属性值是:" arg0.getValue());
System.out.println("新的属性值是:" arg0.getServletContext().getAttribute(arg0.getName()));
}
}
a.jsp
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
/* 添加属性 */
application.setAttribute("username", "zhangsan");
%>
</body>
</html>
b.jsp
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
/* 替换属性 */
application.setAttribute("username", "lisi");
%>
</body>
</html>
c.jsp
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 移除属性 -->
<%
application.removeAttribute("username");
%>
</body>
</html>