Web开发17:Servlet监听器

 

写了一个MyServletContextListener类来测试MyServletContextListener接口。

package com.test.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("context Destroyed invoked "+sce.getServletContext());
	}

	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("context Initialized invoked "+sce.getServletContext());
	}

}

 在启动服务器时,启用信息中会打印出如下信息,说明我们的MyServletContextListener 监听器已监听到服务器的启动

信息: Setting DefaultObjectTypeDeterminer as default ...
context Initialized invoked org.apache.catalina.core.ApplicationContextFacade@10bbf9e

 

在服务器重新加载时,监听器获取到context销毁并立刻初始化的事件。

信息: Reloading this Context has started

context Destroyed invoked org.apache.catalina.core.ApplicationContextFacade@194d372
context Initialized invoked org.apache.catalina.core.ApplicationContextFacade@17b0998

 

接下来再看ServletContextAttributeListener监听器,它用来监听application属性的创建,修改,删除动作。

package com.test.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

public class MyServletContextAttributeListener implements
		ServletContextAttributeListener {

	public void attributeAdded(ServletContextAttributeEvent scab) {
		System.out.println("attribute added");
		System.out.println(scab.getName()+":"+scab.getValue());
	}

	public void attributeRemoved(ServletContextAttributeEvent scab) {
		System.out.println("attribute removed");
		System.out.println(scab.getName()+":"+scab.getValue());
	}

	public void attributeReplaced(ServletContextAttributeEvent scab) {
		System.out.println("attribute replaced");
		System.out.println(scab.getName()+":"+scab.getValue());
	}

}

 

listener.jsp,在此页面中创建一个aa属性,并替换三次

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <body>
  	<%
		application.setAttribute("aa","bb");
		application.setAttribute("aa","cc");
		application.setAttribute("aa","dd");
		application.setAttribute("aa","ee");
  	 %>
  </body>
</html>

  

在管理控制台打印出

attribute added
aa:bb
attribute replaced
aa:bb
attribute replaced
aa:cc
attribute replaced
aa:dd

上面第1,2行表示新建一个属性名是aa且值是bb的属性。

3,4行表示aa属性的值被替换了,旧值是bb(注意,这里只能取出旧值)。余下类似。

listener2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <body>
	<%
		application.removeAttribute("aa");
	 %>
  </body>
</html>

 打开 listener2.jsp页面会在管理控制台打印出如下信息,表示属性被删除了。

attribute removed
aa:ee

 

session的监听器与application的类似,不再一一介绍。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值