通过实现 ServletContextAttributeListener 接口来举例:
实现三个常用的方法:
添加新的属性 void attributeAdded(ServletContextAttributeEvent event) 移除属性 void attributeRenoved(ServletcontextAttribut eEvent event) 替换旧的属性 void attributeReplaced(ServletContextAttributeEvent event)
ServletContextAttributeEvent 可以获取getServletContext 信息,还可以得到添加属性的名称和值
写监听器类:
第一种方法:
paakage cn.itcast.web-listener;
import javax.servlet.ServletContextAttributeEvent;
public class BListener implements ServletContextAttributeListener{
public void attributeAdded (ServletContextAttributeEvent scab){
system.out.println ( "您向 application 中添加了一个名为"+scab.getName()+",值为:"+scab.getValue()+"的属性");
}
public void attributeReplaced(ServletContextAttributeEventacab){
}
public void attributeRemowed(ServletContextAttributeEvent acab){
}
}
在index.jsp页面添加
<%
application.setAttribute("xxx","XXX");
%>
然后访问浏览器,查看控制台打印的效果
第二种方法:
package cn.itcast.web.listener;
import javax.servlet.servletContextAttributeEvent;
public class BListener implements ServletContextAttributeListener{
public void attributeAdded (ServletcontextAttributeEvent scab){
System.out.println("您向 application 中添加了一个名为"+ scab.getName () + ",值为:"+scab.getvalue () +"的属性");
public void attributeReplaced(ServletcontextAttributeEvent scab){
System.out.println (scab.getName() +"=" +scab.getvValue() + ","+ scab.getServletContext().getAttribute(scab.getName()));
}
public void attributeRemoved(ServletContextAttributeEvent scab){
}
}
<%
application.setAttribute ( "xxx","YYY");
%>
第三种方法:
package cn.itcast.web.listener;
import javax.servlet.ServletContextAttributeEvent;
public glass BListener implements ServletContextAttributeListener {
public void attributeAdded(ServletcontextAttributeEvent scab){
System.out.println("您向 application 中添加了一个名为" + scab.getName () + ",值为:"+scab-getValue ( +"的属性");
}
public void attributeReplaced(ServletContextattributeEventscab){
System.out.println(scab.getName()+"=" + scab.getValue()+","+scab.getServletContext().getAttribute(scab.getName()));
}
public void attributeRemoved(ServletContextAttributeEvent acab){
System.out.println (acab.getName() + "=" + scab.getvalue ());
}
}
<%
application.removeAttribute("xxx")
%>
|