06-08
17

servlet上下文监听

servlet上下文:在服务器上使用Session对象来维持同单一客户相关的状态,为多个用户的Web应用维持一个状态时使用Servlet环境(Context).
常用方法:getAttribute(Stringname),getContext(Stringuripath),removeAttribute(String name),setAttribute(String name,Object object)


监听ServletContext的信息:
实现ServletContextListener,ServletContextAttributeListener接口,以便可以监听ServletContext创建,销毁以及它的属性的变化的信息。并且通过private void logout(String message)方法把信息打印到c:\\test.txt文件中。

ServletContext初始化是在服务器启动时,销毁在关闭时。


下面让我们来看以下MyServletContextListener.java这个程序来深入了解以上的知识点。
  

    *´ʵServletContextListenerӿڡ
    */
   public void contextDestroyed(ServletContextEvent sce)
   {
      logout("contextDestroyed()-->ServletContext");
      this.context = null;
   }
   public void contextInitialized(ServletContextEvent sce)
   {
      this.context = sce.getServletContext();
      logout("contextInitialized()-->ServletContextʼ");
   }//ServletContextListener
   /**
    *´ʵ ServletContextAttributeListenerӿ
    */
   public void attributeAdded(ServletContextAttributeEvent scae)
   {
      logout("һServletContextԣattributeAdded('" + scae.getName() + "', '" + scae.getValue() + "')");
   }
   public void attributeRemoved(ServletContextAttributeEvent scae)
   {
      logout("ɾһServletContextԣattributeRemoved('" + scae.getName() + "', '" + scae.getValue() + "')");
   }
   public void attributeReplaced(ServletContextAttributeEvent scae)
   {
      logout("ijServletContextԱı䣺attributeReplaced('" + scae.getName() + "', '" + scae.getValue() + "')");
   }
   private void logout(String message)
   {
      PrintWriter out = null;
      try
      {
         out = new PrintWriter(new FileOutputStream("E:\\dbtest\\test.txt", true));
         out.println(new java.util.Date().toLocaleString() + "::Form ContextListener: " + message);
         out.close();
      }
      catch(Exception e)
      {
         out.close();
         e.printStackTrace();
      }
   }
}

XML配置:

<listener>
       <listener-class>txl.MyServletContextListener</listener-class>
</listener>



JSP测试页

<%
out.println("add attribute");
getServletContext().setAttibute("userName","helking");
out.println("replace attribute");
getServletContext().setAttribute("userName","asiapower");
out.println("remove attribute");
getServletContext().removeAttribute("userName");
%>


文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: servlet 监听
相关日志:
评论: 0 | 引用: 0 | 查看次数: 638
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭