HttpSessionBindingListener会话绑定监听器,首先自定义一个java类 实现 HttpSessionBindingListener接口,构造方法传入name参数,HttpSessionBindingListener中有2个方法valueBound(HttpSessionBindingEvent se) 和 valueUnbound(HttpSessionBindingEvent se)该类对象绑定或解除绑定到会话时候,就会被该监听器监听。绑定指的是调用setAttribute()方法。解除绑定是指调用removesetAttribute()方法,或者会话超,会话失效等。
示例代码:
public class MySessionListener implements HttpSessionBindingListener{
private String name;
public MySessionListener(String name) {
super();
this.name=name;
}
@Override
public void valueBound(HttpSessionBindingEvent se) {
System.out.println("用户上线");
HttpSession session = se.getSession();
ServletContext context = session.getServletContext();
Integer attribute = (Integer) context.getAttribute("onlineUserCounts");
String name = (String) session.getAttribute("name");
if (name!=null) {
if (attribute==null) {
attribute=new Integer(0);
}else {
attribute++;
}
context.setAttribute("onlineUserCounts", attribute);
}
}
@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);
}
}
}
绑定的示例代码(注意:需要把我们自定义的Java类实例化以后存到session里边):
session.setAttribute("SessionListener",new MySessionListener("name") );
最后注意:不需要在xml配置里写代码可直接运行。