概述
https://blog.csdn.net/u011024652/article/details/52293932
https://blog.csdn.net/qq_37651267/article/details/90962152
監聽器作用:
監聽器是Servlet規範中定義的一種特殊類,用於監聽ServletContext、HttpSession和ServletRequest等域對象的創建和銷燬事件,它還可以監聽域對象的屬性發生修改的事件,可以在事件發生前或者發生後做一些必要的處理。
IDEA默認創建的監聽器代碼:
它使用了ServletContextListener,HttpSessionListener, HttpSessionAttributeListener 三個監聽器接口
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener()
public class Listener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
// Public constructor is required by servlet spec
public Listener() {
}
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
}
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
}
// -------------------------------------------------------
// HttpSessionListener implementation
// -------------------------------------------------------
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
}
public void sessionDestroyed(HttpSessionEvent se) {
/* Session is destroyed. */
}
// -------------------------------------------------------
// HttpSessionAttributeListener implementation
// -------------------------------------------------------
public void attributeAdded(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is added to a session.
*/
}
public void attributeRemoved(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is removed from a session.
*/
}
public void attributeReplaced(HttpSessionBindingEvent sbe) {
/* This method is invoked when an attibute
is replaced in a session.
*/
}
}
javax.servlet.http包的監聽器接口:
- HttpSessionActivationListener
- HttpSessionAttributeListener
- HttpSessionBindingListener
- HttpSessionIdListener
- HttpSessionListener
- ServletContextListener
- ServletRequestAttributeListener
- ServletRequestListener
- WriteListener