在web.xml中配置:
<listener> <listener-class>cn.edu.hbcf.common.listener.SessionAttributeListener</listener-class> </listener>
然后写一个实体类:
package cn.edu.hbcf.common.listener; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import cn.edu.hbcf.common.constants.WebConstants; import cn.edu.hbcf.privilege.pojo.BaseUsers; public class SessionAttributeListener implements HttpSessionAttributeListener { public static Map<String, HttpSession> sessionMap=new ConcurrentHashMap<String, HttpSession>(); @Override public void attributeAdded(HttpSessionBindingEvent arg0) { if(arg0.getName().equals(WebConstants.CURRENT_USER)){ // Enumeration session = arg0.getSession().getServletContext().getAttributeNames(); HttpSession session = arg0.getSession(); // ServletContext application = session.getServletContext(); BaseUsers user = (BaseUsers)session.getAttribute(WebConstants.CURRENT_USER); if(sessionMap.containsKey(user.getAccount())){//踢掉前一次登录 try { HttpSession session2=sessionMap.remove(user.getAccount()); session2.invalidate(); } catch (Exception e) { } // application.removeAttribute(user.getAccount()); } sessionMap.put(user.getAccount(), session); // application.setAttribute(user.getAccount(), user); } } @Override public void attributeRemoved(HttpSessionBindingEvent arg0) { } @Override public void attributeReplaced(HttpSessionBindingEvent se) { // TODO Auto-generated method stub } }
时间: 2024-10-13 06:11:02