HttpSessionAttributeListener 监听已登录用户信息

用户提出要求,需要知道哪些用户已经登录,但是在实际环境中,程序被部署到3台web上,前端用f5的负载均衡,那玩意没有玩过,幸好数据库是单一的,所以就简单建立了一个MySQL的内存表(Heap Table),来已经登录的用户信息。

package com.nbrc.lddw.util;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.nbrc.lddw.interceptor.AuthorizeInterceptor;
import com.nbrc.lddw.model.OnlineInfo;
import com.nbrc.lddw.model.User;
import com.nbrc.lddw.service.OnlineUserService;
/**
*
* @author fox
* @date 2009-02-09
* @description 已登录用户的监听
*/
public class OnlineUserListener implements HttpSessionAttributeListener {
private static Log log = LogFactory.getLog(OnlineUserListener.class);

public void attributeAdded(HttpSessionBindingEvent hse) {
log.info("value bound! make session info ...");
HttpSession session = hse.getSession();
ApplicationContext context =
WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext());
OnlineUserService svr = (OnlineUserService)context.getBean("onlineService");
User u = null;
if(session.getAttribute(AuthorizeInterceptor.USR_KEY)!=null)
u = (User) session.getAttribute(AuthorizeInterceptor.USR_KEY);
if(u!=null && svr.findByUserId(u.getId())==null){
OnlineInfo info = new OnlineInfo();
info.setSessionId(session.getId());
info.setUserId(u.getId());
svr.save(info);
}else{
log.error("can't get user in session");
}
}

public void attributeRemoved(HttpSessionBindingEvent hse) {
HttpSession session = hse.getSession();
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext());
OnlineUserService svr = (OnlineUserService)context.getBean("onlineService");
if(svr.findById(session.getId())!=null){
svr.removeById(session.getId());
}
}

public void attributeReplaced(HttpSessionBindingEvent se) {
// TODO Auto-generated method stub

}


}

不过这里还有一个bug,当用户关闭浏览器的时候,还需要将Session里面的内容清除,显示的才是正确的内容。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值