HttpSessionBindingListener的使用

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);
	}

如有相似请联系删稿特别声明

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值