导读:监听器用来监视ServletContext/Session/Request的创建、初始化、销毁以及其中的属性变动。
监听器的分类
常见的主要有以下6个,分别处理Servlet全局、Session和Request。
- ServletContextListener
- ServletContextAttributeListener
- HttpSessionListener
- HttpSessionAttributeListener
- ServletRequestListener
- ServletRequestAttributeListenser
监听器的作用
由于每当一个用户访问一个网站都会产生一个会话或是一个请求,所以可以使用监听器来监视这些会话和请求,能够用于
- 统计在线人数
- 统计访问量
- 应用启动时信息初始化
- 与Spring结合
监听器的实现
根据需要实现上述的六种接口,对象监听器实现Init和Destroy方法,属性监听器实现Add/Remove/Replace方法。然后在web.xml中对监听器进行配置,相比于Servlet和Filter,监听器的配置更为简单。
ServletContextListener举例
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
String appName=sce.getServletContext().getInitParameter("app_name");
String version=sce.getServletContext().getInitParameter("version");
sce.getServletContext().setAttribute("app_name",appName);
sce.getServletContext().setAttribute("version",version);
System.out.println("Init:"+appName+" "+version);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
String appName=(String)sce.getServletContext().getAttribute("app_name");
String version=(String)sce.getServletContext().getAttribute("version");
System.out.println("Destroy:"+appName+" "+version);
}
}
在web.xml中进行配置,设置全局属性,用于获取。
<context-param>
<param-nam