通过实现 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){

}
}

//在新的页面中“xxx”的值改成“YYY”,然后查看控制台的数据是否调用修改的方法
<%
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 ());
}

}

//在最后一个页面删除key,然后在控制台查看是否调用删除属性的方法
<%
application.removeAttribute("xxx")
%>

关注我的公众号SpaceObj 领取idea系列激活码

posted on 2023-05-10 18:09  张伯灵  阅读(26)  评论(0)    收藏  举报