今晚,稍微看了下Java的一些基本知识。说起来惭愧,作为一个Java开发者,居然连基础的jap/servlet都没有学过,只是在印象中有个大概的轮廓而已。于是,趁有时间,赶紧自我修养一下。
servlet API有三个不同级别的监听器接口: ServletContext、HttpSession、 ServletRequest。此外,在servlet 3.0新增了一个监听器接口:Java.servlet.AsyncListener.
注册监听器:
在web.xml上添加一下代码
<listener>
<listener-class>your class</listen-class>
</listener>
在应用程序中,想添加多少个监听器都是可以的,只要你喜欢。
监听器结构:
----ServletContext
----ServletContextListener
(要实现的方法,意思很明显,不说了,就是在)
+ void contextInitialized(ServletContextEvent event)
+void contextDestroyed(ServletContextEvent evnet)
----ServletContextAttributeListener
(要实现的方法,其中参数event可以获取属性名称和方法:getName(), getValue())
+void attributeAdded(ServletContextAttributeEvent event)
+void attributeremoveed(ServletContextAttributeEvent event)
+ void attributereplaced(ServletContextAttributeEvent event)
----HttpSession
----HttpSessionListener
(要实现的方法)
----void sessionCreated(HttpSessionEvent event )
----void sessionDestroyed(HttpSessionEvent event)
----HttpSessionAttributeListener
+void attributeAdded(ServletSessionBindingEvent event)
+void attributeremoveed(ServletSessionBindingEvent event)
+ void attributereplaced(ServletSessionBindingEvent event)
----HttpSessionActivationListener
(这个貌似不太重要的样子,不打字了,好累)
----ServletRequest
----ServletRequestListener
(参数可以使用getServletRequest(),感觉这个会比较有用的样子,可以在统计处理业务请求的时间等等)
+void requestInitialized(ServletRequestEvent event)
+void requestInitialized(ServletRequestEvent event)
----ServletRequestAttributeListener
(意思很明显,不说了)
+void attributeAdded(ServletRequestAttributeEvent event)
+void attributeremoveed(ServletRequestAttributeEvent event)
+ void attributereplaced(ServletRequestAttributeEvent event)
啊,原来用惯了ide,在这里打代码好辛苦啊。。。总算完了。
小结:在以上几个监听器接口中,我们可以看出,几乎是大同小异的。围绕着三大监听器,ServletContext、HttpSession、ServletRequest。他们的生成与销毁,属性的生成和销毁。事实上,我们看名字就已经知道大概含义了,况且我们在eclipse上可以不用记着这几个方法,只要知道有这个接口就可以了。当然,脱离了ide,你就完了。所以,随你们便吧。