---
title: "HttpSessionAttributeListener判断哪些用户已经登陆了"
author: "alwarse"
date: "2012-12-19T09:32:24Z"
tags: ["listener"]
categories: ["Web前端"]
slug: "httpsessionattributelistener"
draft: false
lastmod: "2012-12-19T09:32:57Z"
id: 1750077
url: "https://alwarse.iteye.com/blog/1750077"
---

监听已登录用户信息，需要知道哪些用户已经登录

 

/\**  
 *  
 \*/  
package com.ccc.Listener;

import java.util.ArrayList;  
import java.util.List;

import javax.servlet.http.HttpSessionAttributeListener;  
import javax.servlet.http.HttpSessionBindingEvent;

import com.ccc.util.MessageBean;

 

/\**  
 * @author Administrator  
 *  
 \*/  
public class MessageSessionAttributeListener implements  
  HttpSessionAttributeListener {  
 private static List&lt;String&gt; list = new ArrayList&lt;String&gt;();// 存放用户

 private static List&lt;MessageBean&gt; msglist = new ArrayList&lt;MessageBean&gt;();// 存放信息

 public List&lt;MessageBean&gt; getMsglist() {  
  return msglist;  
 }

 public void attributeAdded(HttpSessionBindingEvent bindingevent) {  
  System.out.println("bindingevent.getName()"+bindingevent.getName());  
  if ("msgUser".equals(bindingevent.getName())) {  
   list.add((String) bindingevent.getValue());  
  }  
  if ("messages".equals(bindingevent.getName())) {  
   msglist.add((MessageBean) bindingevent.getValue());  
  }  
 }

 public void attributeRemoved(HttpSessionBindingEvent bindingevent) {  
  if ("msgUser".equals(bindingevent.getName())) {  
   list.remove(bindingevent.getValue());  
  }

 }

 public void attributeReplaced(HttpSessionBindingEvent bindingevent) {  
  if ("messages".equals(bindingevent.getName())) {  
   msglist.add((MessageBean) bindingevent.getSession().getAttribute(  
     "messages"));  
  }  
 }

 public List&lt;String&gt; getUserList() {  
  return this.list;  
 }

}

 

 

HttpSessionBindingListener和HttpSessionAttributeListener是两个经常让初学者弄混的监听器,其实它们有很大的区别。这2个监听器在文章中简称为BindingListener和AttributeListener.

    1.BindingListener有2个方法,valueBound(HttpSessinBindingEvent)和valueUnbount(HttpSessionBindingEvent)。实现BindingListener接口的对象被绑 定到session时触发valueBound事件,解除绑定时触发valueUnbound事件。举例来说:

 

![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)BindingListener

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->public class UserObject implements HttpSessionBindingListener
{
    public void valueBound(HttpSessionBindingEvent event)
    {
        System.out.println("触发绑定事件!");
    }
    public void valueUnbound(HttpSessionBindingEvent event)
    {
        System.out.println("解除和session的绑定");
    }

}
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

 

UserObject user = new UserObject();

当把该监听器保存到session中，session.setAttribute("user",user)时就会触发valueBound事件.

当该监听器从session中移除时即session.removeAttribute("user"),触发valueUnbound事件;session失效或超时

时也会触发valueUnbound事件。

注意：只有当该监听器(UserObject)保存到session中或从session移除时才会触发事件，其他没有实现该listener对象保存到session时不会触发该事件。

    2.AttributeListener接口有3个方法,attributeAdded(HttpSessionBindingEvent),attributeRemoved(HttpSessionBindingEvent),

attributeReplaced(HttpSeesionEvent)。当在session中添加、移除或更改属性值时会触发相应的事件。

例子：

 

![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)AttributeListener

```

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->MyListener implements HttpSessionAttributeListener
{
    attributeAdded(HttpSessionBindingEvenet event)
    {
         System.out.println("有对象加入session中");
    }
     attributeRemoved(HttpSessionBindingEvent event)
     {
          System.out.println("有对象从session中移除");
     }
     attributeReplaced(HttpSessionBindingEvent event)
     {
          System.out.println("属性值改变");
      }
}
```

 

OtherObject other = new OtherObject();

当有对象添加到session中时，session.setAttribute("object",other)触发attributeAdded事件，

当该对象从session移除时，session.removeAttribute("object")触发attriubteRemoved事件,

当该属性的值发生变化时,  session.replaceAttribute("object",another)触发attributeRepalced事件。

注意：只要有对象保存到session中或从session中移除或改变属性的值都会触发相应事件，不论该对象是否实现了AttributeListener。

 

总结：1.只有实现了HttpSessionBindingListener的类，在和session绑定、解除绑定时触发其事件。

        2.实现了HttpSessionAttributeListener后，任何对象（不论其是否实现了AttributeListener)在变化时均触发对应的事件。

 

 

 

**import** javax.servlet.http.Httpsession;  
**import** javax.servlet.http.HttpSessionAttributeListener;  
**import** javax.servlet.http.HttpSessionBindingEvent;

**public class** SessionAttribListen **implements** HttpSessionAttributeListener {

　/\** Creates new SessionAttribListen \*/  
　**public** SessionAttribListen() {

　　System.out.PRintln(getClass().getName());  
　}

　**public void** attributeAdded(HttpSessionBindingEvent se) {

　　HttpSession session = se.getSession();  
　　String id = session.getId();  
　　String name = se.getName();  
　　String value = (String) se.getValue();  
　　String source = se.getSource().getClass().getName();  
　　String message = **new** StringBuffer("Attribute bound to session in ")  
　　　　.append(source).append("\\nThe attribute name: ").append(name)  
　　　　.append("\\n").append("The attribute value:").append(value)  
　　　　.append("\\n").append("The session ID: ").append(id).toString();  
　　System.out.println(message);  
　}

　**public void** attributeRemoved(HttpSessionBindingEvent se) {

　　HttpSession session = se.getSession();  
　　String id = session.getId();  
　　String name = se.getName();  
　　**if** (name == **null**)  
　　　name = "Unknown";  
　　String value = (String) se.getValue();  
　　String source = se.getSource().getClass().getName();  
　　String message = **new** StringBuffer("Attribute unbound from session in ")  
　　　　.append(source).append("\\nThe attribute name: ").append(name)  
　　　　.append("\\n").append("The attribute value: ").append(value)  
　　　　.append("\\n").append("The session ID: ").append(id).toString();  
　　System.out.println(message);  
　}

　**public void** attributeReplaced(HttpSessionBindingEvent se) {

　　String source = se.getSource().getClass().getName();  
　　String message = **new** StringBuffer("Attribute replaced in session　")  
　　　　.append(source).toString();  
　　System.out.println(message);  
　}  
}