日期:2014-05-18 浏览次数:20808 次
// 这是监听器代码 public class UserListener implements HttpSessionBindingListener { private final static String ON_LINE_USERS = "onLineUsers"; private final static String CURRENT_USER = "currentUser"; private Integer userId; // 当有用户登录时,便把该用户信息保存在当前servlet上下文的map中 public void valueBound(HttpSessionBindingEvent event) { User user = (User) event.getSession().getAttribute(CURRENT_USER); if (null != user) { Map onLineUsers = getMap(event); onLineUsers.put(user.getId(), user); userId = user.getId(); event.getSession().getServletContext().setAttribute(ON_LINE_USERS, onLineUsers); } } // 当有用户退出时,便从当前servlet上下文中清除该用户信息 public void valueUnbound(HttpSessionBindingEvent event) { Map onLineUsers = getMap(event); onLineUsers.remove(userId); event.getSession().getServletContext().setAttribute(ON_LINE_USERS, onLineUsers); } //得到用来存储用户的map对象 public Map getMap(HttpSessionBindingEvent event) { Map map = (Map) event.getSession().getServletContext().getAttribute(ON_LINE_USERS); if (null == map) { map = new HashMap(); } return map; } } // 这是注销的代码(我用了struts1) public ActionForward quit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { request.getSession().setAttribute(CURRENT_USER, null); request.getSession().removeAttribute(USER_LISTENER); return null; }