首先简述下在myeclipse 下创建 监听程序的小过程
在 src 下新建个listener 文件夹,然后在此文件夹下 new -> class 然后在点 add 输入 servletContextlistener 确定就OK 了
最后 修改 web.xml 就完成 了
jsp 页面内容
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<head>
<title>ServletContext监听测试页</title>
</head>
<body>
<%
ServletContext context=pageContext.getServletContext();
context.setAttribute("id","0001");
context.setAttribute("name","lihua");
context.setAttribute("age",10);
context.setAttribute("name","wanglin");
context.removeAttribute("name");
context.removeAttribute("id");
%>
</body>
</html>
监听程序
package listener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener,
ServletContextAttributeListener {
private ServletContext context=null;
public void contextDestroyed(ServletContextEvent arg0) {
logout(":Form ContextListener"+" contestDestroyed()--ServletContext被销毁");
context=null;
}
public void contextInitialized(ServletContextEvent arg0) {
context=arg0.getServletContext();
logout(":Form ContextListener"+" contextInitialized()--ServletContext初始化");
}
public void attributeAdded(ServletContextAttributeEvent arg0) {
logout(":Form ContextAttributeListener"+"增加了一个属性"+arg0.getName()+",值为:"+arg0.getValue());
}
public void attributeRemoved(ServletContextAttributeEvent arg0) {
logout(":Form ContextAttributeListener"+"删除了一个属性"+arg0.getName()+",值为:"+arg0.getValue());
}
public void attributeReplaced(ServletContextAttributeEvent arg0) {
logout(":Form ContextAttributeListener"+"更改了属性值,属性为:"+arg0.getName()+",现值为:"+arg0.getValue());
}
private void logout(String message)
{
try {
PrintWriter out=new PrintWriter(new FileOutputStream("e:/servletContextLog.txt",true));
out.println(new Date()+"::Form ContextListener"+message);
System.out.println(new Date()+message);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>listener.MyServletContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>