1.4、ServletContextAttributeListener监听器范例

468 篇文章 0 订阅

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)中的属性值的变化情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值