监听器:
1、概念:Servlet规范中的一种 特殊类,用于监听ServletContext,HttpSession和servletRequest等域对象的创建销毁事件,用于监听域对象的属性发生修改的事件,可以在事件发生前和事件发生后做一些必要的处理。
2、Listener的运行原理:
3、Listener和Filter以及Servlet的执行顺序
4、程序举例:
package com.westos.listener;
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;
public class TestListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
// Public constructor is required by servlet spec
public TestListener() {
}
// -------------------------------------------------------
// 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.
*/
System.out.println("应用程序启动"+sce.getServletContext());
}
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
System.out.println("应用程序关闭");
}
// -------------------------------------------------------
// HttpSessionListener implementation
// -------------------------------------------------------
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
System.out.println("session创建"+se.getSession().getId());
}
public void sessionDestroyed(HttpSessionEvent se) {
/* Session is destroyed. */
System.out.println("session销毁"+se.getSession().getId());
}
// -------------------------------------------------------
// HttpSessionAttributeListener implementation
// -------------------------------------------------------
public void attributeAdded(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is added to a session.
*/
System.out.println("session新增加属性"+sbe.getName()+"其值为:"+sbe.getValue());
}
public void attributeRemoved(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is removed from a session.
*/
System.out.println("session删除属性"+sbe.getName()+"其值为:"+sbe.getValue());
}
public void attributeReplaced(HttpSessionBindingEvent sbe) {
/* This method is invoked when an attibute
is replaced in a session.
*/
System.out.println("session替换属性"+sbe.getName()+"其值为:"+sbe.getValue());
}
}