---
title: "Servlet监听器"
author: "ashnl007"
date: "2014-06-25T21:52:12Z"
tags: ["Servlet", "监听器"]
categories: ["编程语言"]
slug: "servlet"
draft: false
lastmod: "2014-06-25T21:55:22Z"
id: 2085114
url: "https://ashnl007.iteye.com/blog/2085114"
---

1、Servlet Context 监听器

1.1、ServletContextListener

         ServletContextListener有两个方法：

 

```
  void contextInitialized(ServletContextEvent event) 
```

 

    servlet上下文创建的时候会调用此方法；

 

```
  void contextDestroyed(ServletContextEvent event)
```

 

    反之，servlet上下文被销毁的时候会调用此方法；event可以获取ServletContext实例。

1.2、ServletContextAttributeListener

   此接口是和Servlet上下文的中的attribute有关、该接口中有3个方法：

 

```
void attributeAdded(ServletContextAttributeEvent event)
void attributeRemoved(ServletContextAttributeEvent event)
void attributeReplaced(ServletContextAttributeEvent event)
```

 

    分别Servlet上下文中属性添加、移除、替换后触发。ServletContextAttributeEvent 可以获取相应的属性名称和值event.getName()、event.getValue()。

 

 

2、Session 监听器

2.1 HttpSessionListener

 

```
//session创建时触发
void sessionCreated(HttpSessionEvent event)
//session销毁时触发
void sessionDestroyed(HttpSessionEvent event)
```

 

    HttpSessionEvent可以获取到当前session。

2.2 HttpSessionAttributeListener

```
void attributeAdded(HttpSessionBindingEvent event)
void attributeRemoved(HttpSessionBindingEvent event)
void attributeReplaced(HttpSessionBindingEvent event)
```

   分别Sesson中属性添加、移除、替换后触发。HttpSessionBindingEvent可以获取相应的属性名称和值event.getName()、event.getValue()和session。

2.3 HttpSessionActivationListener

```
//激活
sessionDidActivate(HttpSessionEvent event)
//被传送到别的jvm或 写到硬盘  
sessionWillPassivate(HttpSessionEvent event)
```

   该接口一般在分布式环境下使用、为了节省内存、将使用较少的对象序列化到硬盘等存储设备中、HttpSessionEvent可以获取当前session。 

2.4 HttpSessionBindingListener

```
void valueBound(HttpSessionBindingEvent event)
void valueUnbound(HttpSessionBindingEvent event)
```

  实现该接口的对象，该对象的实例在保存到session或者session移除时会收到通知、然后执行相应的方法、HttpSessionBindingEvent可以获取当前session、属性值和属性名。 

 

 

3、Servlet Request监听器

3.1 ServletRequestListener

```
//用户请求到达、被初始化时触发该方法
void requestInitialized(ServletRequestEvent event)
//用户请求结束、被销毁时触发该方法
void requestDestroyed(ServletRequestEvent event)
```

    ServletRequestEvent可以返回当前request和ServletContext 

 3.2 ServletRequestAttributeListener

    该接口用于监听ServletRequest（request）范围内属性的变化，分别对应Request中属性添加、移除和替换：

```
void attributeAdded(ServletRequestAttributeEvent event)
void attributeRemoved(ServletRequestAttributeEvent event)
void attributeReplaced(ServletRequestAttributeEvent event)
```

    ServletRequestAttributeEvent可以返回属性名和属性值