通过实现 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") %>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)