HttpSessionBindingListener的学习
Interface HttpSesssionBindingListenner extends EventListener;
api文档关于这个接口的介绍是:使对象在被绑定到会话或从会话中取消对它的绑定时得到通知。该对象通过 HttpSessionBindingEvent
对象得到通知。这可能是 servlet 编程人员显式从会话中取消绑定某个属性的结果(由于会话无效,或者由于会话超时)。
这个接口有两个方法:1. void valueBound(HttpSessionBindingEvent event) 2. void valueUnbound(HttpSessionBindingEvent event) .
HttpSesssionBindingListenner 继承自EventListener接口,而EventListener接口是这样的:
public interface EventListener :A tagging interface that all event listener interfaces must extend. 这句话表明EventListener只是个标记接口,和Cloneable,Serializable类似;这个接口只是用来标记该事件监听器的接口。具体使用如下:
javabean实现HttpSesssionBindingListenner 接口并实现它的两个方法,当对象别绑定到会话时或从会话中取消对他的绑定时得到通知,即调用该javabean对象的这两个方法。
1 import javax.servlet.http.HttpSessionBindingEvent; 2 import javax.servlet.http.HttpSessionBindingListener; 3 public class User implements HttpSessionBindingListener{ 4 private String name; 5 private String pwd; 6 private UserList userList=UserList.getInstance(); 7 public User() { 8 // TODO Auto-generated constructor stub 9 } 10 public User(String name, String pwd) { 11 super(); 12 this.name = name; 13 this.pwd = pwd; 14 } 15 public String getName() { 16 return name; 17 } 18 public void setName(String name) { 19 this.name = name; 20 } 21 public String getPwd() { 22 return pwd; 23 } 24 public void setPwd(String pwd) { 25 this.pwd = pwd; 26 } 27 @Override 28 public String toString() { 29 return "User [name=" + name + ", pwd=" + pwd + "]"; 30 } 31 public void valueBound(HttpSessionBindingEvent arg0) { 32 // TODO Auto-generated method stub 33 this.userList.addUser(this); 34 System.out.println(this.name+"上线了!目前在线人数为:"+this.userList.getCount()); 35 } 36 public void valueUnbound(HttpSessionBindingEvent arg0) { 37 // TODO Auto-generated method stub 38 this.userList.removeUser(this); 39 System.out.println(this.name+"下线了!目前在线人数为:"+this.userList.getCount()); 40 } 41 }
工具类:
1 import java.util.ArrayList; 2 import java.util.List; 3 public class UserList { 4 private static UserList userList=new UserList(); 5 private List<User> list=new ArrayList<User>(); 6 private UserList() { 7 // TODO Auto-generated constructor stub 8 } 9 public static UserList getInstance(){ 10 return userList; 11 } 12 public void addUser(User user){ 13 list.add(user); 14 } 15 public void removeUser(User user){ 16 list.remove(user); 17 } 18 public int getCount(){ 19 return list.size(); 20 } 21 }
以上就是关于 HttpSesssionBindingListenner 接口的学习。。。。。。