案例:监听域对象的属性变更

案例:监听域对象的属性变更,第1张

案例:监听域对象的属性变更 创建测试页面testattribute.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>


测试域对象属性变更事件监听器


	这是一个测试域对象属性变更事件监听器的页面
	<%
		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");
	%>


创建监听器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中配置监听器
  
    
		cn.itcast.chapter08.listener.MyAttributeListener
	
  
启动Tomcat,测试

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5575076.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存