`

Servlet监听器

web 
阅读更多

    Servlet API中定义了8个监听器接口,可以用于监听ServletContext,HttpSession和ServletRequest对象的生命周期事件,以及这些对象的属性改变.

    目前Servlet2.4和JSP2.0总共有8个监听器接口和6个Event类,其中HttpSessionAttributeListener与HttpSessionBindingListener皆使用HttpSessionBindingEvent;HttpSessionListener和HttpSessionActivationListener则都使用HttpSessionEvent;其余Listener对应的Event如下所示:

 

 

ServletContextListener 接口

    该接口主要用于监听Web应用程序启动,销毁.该接口可用于Web应用程序启动时执行一些初始化的任务.

    该接口提供了如下方法:

public void contextInitialized(ServletContextEvent sce)

当Web应用程序初始化进程开始时,Web容器调用这个方法.该方法将在所有过滤器和Servlet初始化之前被调用.

 

void contextDestroyed(ServletContextEvent sce)

当Servlet上下文将要被关闭时,Web容器调用这个方法.该方法将在所有的Servlet和过滤器销毁之后调用.

 

 

ServletContextEvent类

    Web容器通过ServletContextEvent对象来通知实现了ServletContextListener接口的监听器,监听器可以利用ServletContextEvent类来得到ServletContext对象.

    除了构造方法,该类只有一个方法:

public ServletContext getServletContext()

该方法用于得到ServletContext对象.

 

 

    要让Web应用程序启动时通知监听器,需要在Web.xml的<linstener>元素中配置监听器类.在配置监听器时,不需要告诉容器实现了什么监听器接口.容器会自动识别.

 

 

 

HttpSessionBindingListener接口

    如果一个对象实现了 HttpSessionBindingListener 接口,当该对象被绑定到Session中或者从Session中被删除时,Servlet容器会通知该 HttpSessionBindingListener对象.这个对象在接收到通知后,可以做一些初始化或清除状态的操作.

    HttpSessionAttributesListener接口提供如下方法:

public void valueBound(HttpSessionBindingEvent event)

当对象被绑定到Session中,Servlet容器调用这个方法通知该对象.

 

public void valueUnbound(HttpSessionBindingEvent event)

当从Session中删除对象时,Servlet容器调用这个方法来通知该对象.

 

 

HttpSessionBindingEvent类

    Servlet容器通过HttpSessionBindingEvent对象来通知实现HttpSessionBindingListener接口的对象.而对象可以利用HttpSessionBindingEvent对象来访问与它相联系的HttpSession对象.

    javax.servlet.http.HttpSessionBindingEvent类的方法:

public HttpSessionBindingEvent(HttpSession session,java.lang.String name)

public HttpSessionBindingEvent(HttpSession session,java.lang.String name,java.lang.Object value)

构造方法,当一个对象绑定到Session中或从Session中被删除时,容器使用该事件对象通知监听器.

 

public java.lang.String getName()

返回绑定到Session中或者从Session中删除的属性的名字.

 

public java.lang.Object getValue()

返回被添加,删除,或替换的属性的值.如果属性被添加或者被删除,该方法返回属性的值.如果属性被替换,该方法返回属性先前的值.

 

public HttpSession getSession()

返回HttpSession对象.

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics