用于监听用户会话对象(HttpSession)的事件监听器
用于监听请求消息对象(ServletRequest)的事件监听器
二、按监听的事件划分:
监听域对象自身的创建和销毁的事件监听器
监听域对象中的属性的增加和删除的事件监听器如s(setAttribute,removeAttribute)
监听绑定到HttpSession域中某个对像的状态的事件监听器
监听域对象自身的创建和销毁的事件监听器:
ServletContextListener:主要用于全局变量的操作数据库的连接操作
package nuc.edu.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/*
* ServletContext自身创建和关闭时的监听器
*/
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("contextDestroyed");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("contextInitialized");
String name=arg0.getServletContext().getInitParameter("name");//用于获取web.xml中的参数
System.out.println("param-name:name---param-value:"+name);
}
}
启动tomcat时的输出:
contextInitializedparam-name:name---param-value:熊丰
web.xml中的设置:注册监听器和放在xml中的所需要的初始化参数
<listener>
<listener-class>nuc.edu.listener.MyServletContextListener</listener-class>
</listener>
<context-param>
<param-name>name</param-name>
<param-value>熊丰</param-value>
</context-param>
HttpSessionListener:该监听器主要用于统计在线人数和记录访问信息(ip、时间)
package nuc.edu.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/*
* HttpSession对象创建和销毁时的监听器
*/
public class MyHttpSessionListener implements HttpSessionListener {
//打开不同的浏览器时自动创建不同session
@Override
public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("sessionCreated----"+arg0.getSession().getId());
}
//session到期、或者调用arg0.getSession().invalidate()、或者tomacat关闭
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
System.out.println("sessionDestroyed----"+arg0.getSession().getId());
}
}
web.xml:
<listener>
<listener-class>nuc.edu.listener.MyHttpSessionListener</listener-class>
</listener>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
打开浏览器和到期:
ServletRequestListener:
代码:
package nuc.edu.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyServeltRequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent arg0) {
System.out.println("requestDestroyed");
}
@Override
public void requestInitialized(ServletRequestEvent arg0) {
System.out.println("requestInitialized");
}
}
requestInitialized
sessionCreated----5F41368F81205C001DB79838583DCFA1
requestDestroyed