ServletContext事件处理的实现问题
package web1Pac;
import java.io.FileOutputStream;
import java.io.PrintWriter;
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 contextInitialized(ServletContextEvent s)
{
this.context=s.getServletContext();
print("ServletContext初始化......");
}
public void contextDestroyed(ServletContextEvent s)
{ this.context = null;
print("ServletContext被释放......");
}
public void attributeAdded(ServletContextAttributeEvent sa)
{
print("增加ServletContext对象的一个属性:attributeAdded('"+sa.getName()+"',' "+sa.getValue
()+"')");
}
public void attributeRemoved(ServletContextAttributeEvent sa)
{
print("删除ServletContext对象的某一个属性:attributeRemoved('"+sa.getName()+"','"+"')");
}
public void attributeReplaced(ServletContextAttributeEvent sa)
{
print("更改ServletContext对象的某一个属性:attributeReplaced('"+sa.getName
()+"','"+sa.getValue()+"')");
}
private void print(String message)
{
PrintWriter out = null;
try{
out = new PrintWriter(new FileOutputStream("D:\\test.txt",true));
out.println(new java.util.Date().toString()+" ContextListener: "+message);
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
上面的程序是测试ServletContext的事件监听,我是用springsource来编写的。在另一个页面写了一个
JSP程序来操作ServletContext的属性
<body>
<% out.println("Test ServletContextListener");
application.setAttribute("userid","zzb");
application.setAttribute("userid","zzb2");
application.removeAttribute("userid");
%>
</body>
这只是jsp的主要代码,运行jsp代码时输出了第一句"Test ServletContextListener",查看D:\\test.txt
里面什么都没有,这个该怎么改,才能把消息写入目标文件中??
------解决方案--------------------同学。你查看API撒。写和打印不太一样把。。。
------解决方案--------------------监听需要在web.xml里注册吧,我记得