1.4、ServletContextAttributeListener监听器范例:
编写ServletContextAttributeListener监听器监听ServletContext域对象的属性值变化情况,代码如下:
1 package me.gacl.web.listener; 2 3 import java.text.MessageFormat; 4 5 import javax.servlet.ServletContextAttributeEvent; 6 import javax.servlet.ServletContextAttributeListener; 7 8 /** 9 * @ClassName: MyServletContextAttributeListener 10 * @Description: ServletContext域对象中属性的变更的事件监听器 11 * @author: 孤傲苍狼 12 * @date: 2014-9-11 下午10:53:04 13 * 14 */ 15 public class MyServletContextAttributeListener implements 16 ServletContextAttributeListener { 17 18 @Override 19 public void attributeAdded(ServletContextAttributeEvent scab) { 20 String str =MessageFormat.format( 21 "ServletContext域对象中添加了属性:{0},属性值是:{1}" 22 ,scab.getName() 23 ,scab.getValue()); 24 System.out.println(str); 25 } 26 27 @Override 28 public void attributeRemoved(ServletContextAttributeEvent scab) { 29 String str =MessageFormat.format( 30 "ServletContext域对象中删除属性:{0},属性值是:{1}" 31 ,scab.getName() 32 ,scab.getValue()); 33 System.out.println(str); 34 } 35 36 @Override 37 public void attributeReplaced(ServletContextAttributeEvent scab) { 38 String str =MessageFormat.format( 39 "ServletContext域对象中替换了属性:{0}的值" 40 ,scab.getName()); 41 System.out.println(str); 42 } 43 }
在web.xml文件中注册监听器
1 <listener> 2 <description>MyServletContextAttributeListener监听器</description> 3 <listener-class>me.gacl.web.listener.MyServletContextAttributeListener</listener-class> 4 </listener>
编写ServletContextAttributeListenerTest.jsp测试页面
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML> 3 <html> 4 <head> 5 <title>ServletContextAttributeListener监听器测试</title> 6 </head> 7 8 <body> 9 <% 10 //往application域对象中添加属性 11 application.setAttribute("name", "孤傲苍狼"); 12 //替换application域对象中name属性的值 13 application.setAttribute("name", "gacl"); 14 //移除application域对象中name属性 15 application.removeAttribute("name"); 16 %> 17 </body> 18 </html>
运行结果如下:
从运行结果中可以看到,ServletContextListener监听器成功监听到了ServletContext域对象(application)中的属性值的变化情况。