最初のリスナーとリスナーのコンテンツの出力

3417 ワード

まず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>