共计 2759 个字符,预计需要花费 7 分钟才能阅读完成。
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
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
<%@ 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
<%@ 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
<%@ 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>