javaWeb监听对象域属性变化(6)

好记性不如烂笔头42-javaWeb监听对象域属性变化(6) JavaWeb中对象域的属性的变更的事件监听器,可以用来监听 ServletContext, HttpSession, HttpServletRequest 这三个对象中的属性变更信息事件的监听器。 这三个监听器接口分别是ServletContextAttributeListener, HttpSessionAttributeListener 和ServletRequestAttributeListener,这三个接口中都定义了三个方法来处理被监听对象中的属性的增加,删除和替换的事件,同一个事件在这三个接口中对应的方法名称完全相同,只是接受的参数类型不同。 1、 attributeAdded 方法 当向被监听对象中增加一个属性时,web容器就调用事件监听器的attributeAdded方法进行响应,这个方法接收一个事件类型的参数,监听器可以通过这个参数来获得正在增加属性的域对象和被保存到域中的属性对象 各个域属性监听器中的完整语法定义为: 1 public void attributeAdded(ServletContextAttributeEvent scae) 2 public void attributeReplaced(HttpSessionBindingEvent hsbe) 3 public void attributeRmoved(ServletRequestAttributeEvent srae)

2、 attributeRemoved 方法 当删除被监听对象中的一个属性时,web容器调用事件监听器的attributeRemoved方法进行响应 各个域属性监听器中的完整语法定义为: 1 public void attributeRemoved(ServletContextAttributeEvent scae) 2 public void attributeRemoved (HttpSessionBindingEvent hsbe) 3 public void attributeRemoved (ServletRequestAttributeEvent srae)

3、 attributeReplaced 方法 当监听器的域对象中的某个属性被替换时,web容器调用事件监听器的attributeReplaced方法进行响应   各个域属性监听器中的完整语法定义为: 1 public void attributeReplaced(ServletContextAttributeEvent scae) 2 public void attributeReplaced (HttpSessionBindingEvent hsbe) 3 public void attributeReplaced (ServletRequestAttributeEvent srae)

4、 编写监听ServletContext域对象的属性变化的源代码 实现ServletContextAttributeListener接口,监听对象域属性的变化

package com.servlet.listener;import java.text.MessageFormat;import javax.servlet.ServletContextAttributeEvent;import javax.servlet.ServletContextAttributeListener;/** * 简单实现ServletContextAttributeListener接口,监听对象域属性的变化 * @author 范芳铭 */{(ServletContextAttributeEvent scab) {String str =MessageFormat.format(“ServletContext域对象中添加了属性:{0},属性值是:{1}”,scab.getName(),scab.getValue());System.out.println(str);}(ServletContextAttributeEvent scab) {String str =MessageFormat.format(“ServletContext域对象中删除属性:{0},属性值是:{1}”,scab.getName(),scab.getValue());System.out.println(str);}(ServletContextAttributeEvent scab) {String str =MessageFormat.format(“ServletContext域对象中替换了属性:{0}的值,原始值为{1}”,scab.getName(),scab.getValue());System.out.println(str);}}

5、 修改web.xml

>com.servlet.listener.EasyServletContextAttributeListener</listener-class> </listener>

6、 测试用的index.jsp

>><body>HttpSession创建后的Id是:${pageContext.session.id}<br><%//往application域对象中添加属性application.setAttribute(“name”, “ffm”);//替换application域对象中name属性的值application.setAttribute(“name”, “123”);//移除application域对象中name属性application.removeAttribute(“name”);%></body></html>

7、 运行结果 启动WEB中间件,从URL访问: :8080/webStudy/index.jsp 控制台输结果: ServletContext域对象中添加了属性:name,属性值是:ffm ServletContext域对象中替换了属性:name的值,原始值为ffm ServletContext域对象中删除属性:name,,属性值是:123

8、 其他 因为这三个对象域的实现方式类似,因此其他两个具体的实现也可以完全参考本源代码;

心中有愿望一定要去闯,努力实现最初的梦想,

javaWeb监听对象域属性变化(6)

相关文章:

你感兴趣的文章:

标签云: