WEB-INF\src\MyServletContextAttributeListener.java
package sadhu; import javax.servlet.annotation.*; import javax.servlet.*; /** application范围属性监听类 */ public class MyServletContextAttributeListener implements ServletContextAttributeListener { //当程序像application范围添加属性时触发该方法 public void attributeAdded(ServletContextAttributeEvent event) { ServletContext application = event.getServletContext(); String name = event.getName(); Object value = event.getValue(); System.out.println(application+"范围内添加了名为"+name+",值为"+value+"的属性!"); } //当application范围内的属性被移出的时候触发该方法 public void attributeRemoved(ServletContextAttributeEvent event) { ServletContext application = event.getServletContext(); String name = event.getName(); Object value = event.getValue(); System.out.println(application+"范围内的名为"+name+",值为"+value+"的属性被删除了!"); } //当application范围的属性被替换时触发该方法 public void attributeReplaced(ServletContextAttributeEvent event) { ServletContext application = event.getServletContext(); String name = event.getName(); Object value = event.getValue(); System.out.println(application+"范围内名为"+name+",值为"+value+"的属性被替换了!"); } }
WEB-INF\web.xml
<?xml version="1.0" encoding="utf8" ?> <web-app version="2.5" xmls="http://java.sun.com/xml/ns/j2ee" xmls:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"> <listener> <listener-class>sadhu.MyListener</listener-class> </listener> <listener> <listener-class>sadhu.MyServletContextAttributeListener</listener-class> </listener> </web-app>
index.jsp
<body> sadas <% application.setAttribute("name","张三"); %> </body>
控制台输出:
org.apache.catalina.core.ApplicationContextFacade@516810a5范围内添加了名为org.ap
ache.jasper.runtime.JspApplicationContextImpl,值为org.apache.jasper.runtime.JspA
pplicationContextImpl@5d664719的属性!
org.apache.catalina.core.ApplicationContextFacade@516810a5范围内添加了名为name,
值为张三的属性!