HttpSessionBindingListener,HttpSessionListener的用法

1、HttpSessionListener

添加类OnlineUserListener,继承HttpSessionListener,HttpSessionListener中有两个方法sessionCreated(HttpSessionEvent event)与sessionDestroyed(HttpSessionEvent event),前者是监听session的新建,后者是监听session的销毁。

一旦监听器发现调用了sessionDestoryed方法就会把其用户从在线人数中delete,在下面两种情况下会发生sessionDestoryed事件

a.执行session.invalidate()方法时

logout.jsp中调用了 session.invalidate()方法

b.session会话超时

session的默认超时事件是30分钟,30分钟后自动销毁session

2、HttpSessionBindingListener

HttpSessionBindingListener虽然叫做监听器,但使用方法与HttpSessionListener完全不同。我们实际看一下它是如何使用的。

新建类OnlineUserBindingListener,实现HttpSessionBindingListener接口,构造方法传入username参数,HttpSessionBindingListener内有两个方法valueBound(HttpSessionBindingEvent event)和valueUnbound(HttpSessionBindingEvent event),前者为数据绑定,后者为取消绑定

所谓对session进行数据绑定,就是调用session.setAttribute()把HttpSessionBindingListener保存进session中。

HttpSessionBindingListener和HttpSessionListener之间的最大区别:HttpSessionListener只需要设置到web.xml中就可以监听整个应用中的所有session。HttpSessionBindingListener必须实例化后放入某一个session中,才可以进行监听。

从监听范围上比较,HttpSessionListener设置一次就可以监听所有session,HttpSessionBindingListener通常都是一对一的。

正是这种区别成就了HttpSessionBindingListener的优势,我们可以让每个listener对应一个username,这样就不需要每次再去session中读取username,进一步可以将所有操作在线列表的代码都移入listener,更容易维护。

valueUnbound的触发条件是以下三种情况:

a.执行session.invalidate()时。

b.session超时,自动销毁时。

c.执行session.setAttribute("onlineUserListener", "其他对象");或session.removeAttribute("onlineUserListener");将listener从session中删除时。

 

项目中使用hmailserver实现邮件的收发,处理邮件的附件上传到服务器临时目录需要在用户退出系统时把对应的邮件附件删除,这个HttpSessionBindingListener刚好可以实现这一功能,一对一的,当退出的时候把应对用户的附件删除,赶紧上代码:

	class CleanUp implements HttpSessionBindingListener {

		public void valueBound(HttpSessionBindingEvent httpsessionbindingevent) {
		}

		public void valueUnbound(HttpSessionBindingEvent httpsessionbindingevent) {
			File file = new File(m_filename);
			if (file != null)
				file.delete();
		}

		String m_filename;

		public CleanUp(String s) {
			m_filename = null;
			m_filename = s;
		}
	}

 设置session,以便退出系统的时候删除对应文件

	public void setAttachFiles(HttpServletRequest httpservletrequest,Map<String,String> fs) throws Exception {
		Iterator<?> iterator=fs.entrySet().iterator();
		HttpSession _session=httpservletrequest.getSession();
		while(iterator.hasNext())
		{
			Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
			CleanUp clearUp=new CleanUp(entry.getKey().toString());
			_session.setAttribute(UUID.randomUUID().toString(), clearUp);
			setAttachFile(entry.getKey().toString(),entry.getValue().toString());
		}
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值