servlet监听器
导读模块:虽然监听器的作用很强大,但是servlet中并没有相关的实现类,只是有一些接口,而这也恰恰体现出了servlet的灵活性
- servlet中的监听器主要是针对request,session,servletContext开展的
- 监听听器要想起作用则必须要有实现类,而实现类要起作用,则必须要有动作,所谓的动作其实就是事件,所谓的事件就是与之关联的一些类
- servlet中一共有8个监听器接口,6个事件
ServletContextListener接口
接口方法
方法名 |
作用 |
触发场景 |
contextInitialized(ServletContextEvent sce) |
可以初始化一下数据比入初始化Dao工具类 |
当Container启动的时候调用这个方法 |
contextDestroyed(ServletContextEvent sce) |
关闭一些类对象 |
当容器移除Web应用程序时,会呼叫contextDestroyed ()方法 |
ServletContextEvent 对象的操作
getServletContext();
Web.xml 标签
<listener>
<listener-class>cn.qsub.ReadContext</listener-class>
</listener>
使用注意
- 如果contextDestroyed不执行多是因为tomcat没有正常关闭或是没有实现ServletContextListener接口,或者web.xml配置类路径出错了。在Eclipse关闭tomcat的正确方法是:点击右键点关闭
ServletContextAttributeListener接口
接口方法
方法名 |
作用 |
触发场景 |
attributeAdded(ServletContextAttributeEvent arg0) |
监听application对象中的属性变更 |
当有对象加入为application(ServletContext)对象的属性 |
attributeReplaced(ServletContextAttributeEvent arg0) |
监听application对象中的属性变更 |
当有对象置换为application(ServletContext)对象的属性 |
attributeRemoved(ServletContextAttributeEvent arg0) |
监听application对象中的属性变更 |
当有对象移除为application(ServletContext)对象的属性 |
ServletContextAttributeEvent事件
public String getName();
public Object getValue();
web.xml标签
<listener>
<listener-class>cn.qsub.MyServletContextAttributeListener</listener-class>
</listener>
示例代码
@WebListener
public class MyServletContextAttributeListener implements ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent event) {
ServletContext application=event.getServletContext();
String name=event.getName();
Object value=event.getValue();
System.out.println(application+"范围内添加了名为"+name+"值为"+value+"的属性");
}
@Override
public void attributeRemoved(ServletContextAttributeEvent event) {
ServletContext application=event.getServletContext();
String name=event.getName();
Object value=event.getValue();
System.out.println(application+"范围内名为"+name+"值为"+value+"的属性被删除了");
}
@Override
public void attributeReplaced(ServletContextAttributeEvent event) {
ServletContext application=event.getServletContext();
String name=event.getName();
Object value=event.getValue();
System.out.println(application+"范围内"+name+"值为"+value+"的属性被替换了");
}
}
ServletRequestListener接口
- 用户响应监听器,用于对Request请求进行监听(创建、销毁)
接口方法
方法名 |
作用 |
触发事件 |
requestInitialized(ServletRequestEvent arg0) |
- |
对销毁客户端进行监听,即当执行request.removeAttribute(“XXX”)时调用 |
requestDestroyed(ServletRequestEvent arg0) |
- |
对销毁客户端进行监听,即当执行request.removeAttribute(“XXX”)时调用 |
ServletRequestEvent事件
public ServletRequest getServletRequest();