HttpSessionBindingListener:会话绑定监听器,当类实现了HttpSessionBindingListener接口后,
该类对象绑定或解除到会话时,就会被该监听器监听。
绑定指的是调用setAttribute()方法。解除绑定是指调用removesetAttribute()方法,或者会话超,会话失效等。
绑定(调用session.setAttribute()把HttpSessionBindingListener放进session中)
// 把用户名放入在线列表
session.setAttribute(“sessionListener”, new MySessionListener(username));
定义一个java类 叫:MySessionListener,实现了HttpSessionBindingListener接口
接口中共定义了两个方法:valueBound()和valueUnbound(),分别对应数据绑定,
和取消绑定两个事件。
valueBound()方法的代码如下:
private String userName;
public MySessionListener(String userName) {
super();
this.userName = userName;
}
@Override
public void valueBound(HttpSessionBindingEvent se) {
//System.out.println("会话开始");
HttpSession session = se.getSession();
ServletContext context = session.getServletContext();
Integer attribute = (Integer) context.getAttribute("onlineUserCounts");
if(userName != null) {
if(attribute == null) {
attribute = Integer.valueOf(1);
}else {
attribute++;
}
context.setAttribute("onlineUserCounts", attribute);
}
}
valueUnbound()方法,代码如下:
@Override
public void valueUnbound(HttpSessionBindingEvent se) {
//System.out.println("会话结束");
HttpSession session = se.getSession();
ServletContext context = session.getServletContext();
Integer attribute = (Integer) context.getAttribute("onlineUserCounts");
if(attribute != null) {
attribute--;
}
context.setAttribute("onlineUserCounts", attribute);
}
如有相似请联系删稿特别声明